先到官网了解mybatis的语法:https://mybatis.org/mybatis-3/zh/sqlmap-xml.html

前端用了thymeleaf和vue.js,效果图和demo地址:https://gitee.com/cainiaoA/mybatis

thymeleaf获取java请求头  ctx='http://localhost:8017/
<script th:inline="javascript"> var ctx = [[@{/}]]; </script>

然后在pom.xml添加相关的引用

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.tushu</groupId>
<artifactId>tushu</artifactId>
<version>1.0.0</version>
<name>tushu</name>
<description>练习</description> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<!--spring-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-data-jpa</artifactId>-->
<!--</dependency>-->
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>5.1.21</scope>
</dependency> <!--引入druid-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency> <dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
<version>1.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.13</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-beta9</version>
</dependency> <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.0.Alpha6</version>
</dependency> <!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- elastic search -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- 用了 elasticsearch 就要加这么一个,不然要com.sun.jna.Native 错误 -->
<dependency>
<groupId>com.sun.jna</groupId>
<artifactId>jna</artifactId>
<version>3.0.9</version>
</dependency> <!-- thymeleaf legacyhtml5 模式支持 -->
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency> <dependency>
<groupId>net.minidev</groupId>
<artifactId>json-smart</artifactId>
<version>2.2.1</version>
</dependency> <!--测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency> <!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- hsqldb -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
</dependency>
</dependencies>
<!--打包成插件-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

然后编写application.yml的相关配置

server:
port: 8017 spring:
datasource:
# 数据源基本配置
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
jackson:
date-format: yyyy-MM-dd HH:mm:ss #如果使用字符串表示,用这行设置格式
timezone: GMT+8
serialization:
write-dates-as-timestamps: false #使用时间戳,使用数值timestamp表示日期 mybatis:
# 搜索指定包别名
typeAliasesPackage: com.tushu.**.domain
# 指定全局配置文件位置
config-location: classpath:mybatis/mybatis-config.xml
# 指定sql映射文件位置
mapper-locations: classpath:mybatis/mapper/*Mapper.xml

mybatis相关配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration> <settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
</configuration>

然后就行相关的ioc和mybatis的数据文件操作

先编写domain,就是数据的model

package com.tushu.book.domain;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map; public class BaseEntity implements Serializable { /** 请求参数 */
private Map<String, Object> params; public Map<String, Object> getParams()
{
if (params == null)
{
params = new HashMap<>();
}
return params;
} public void setParams(Map<String, Object> params)
{
this.params = params;
}
}
package com.tushu.book.domain;

import java.util.Date;

public class books extends BaseEntity {
/**
* 编号
*/
private int id;
/**
* 书名
*/
private String title;
/**
* 价格
*/
private double price;
/**
* 出版日期
*/
private Date publishDate; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public double getPrice() {
return price;
} public void setPrice(double price) {
this.price = price;
} public Date getPublishDate() {
return publishDate;
} public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
} @Override
public String toString() {
return "books{" +
"id=" + id +
", title='" + title + '\'' +
", price=" + price +
", publishDate=" + publishDate +
'}';
}
}

然后编写mybatis数据操作,接口文件格式(xxxMapper.java)

package com.tushu.book.mapper;

import com.tushu.book.domain.books;

import java.util.List;

public interface BooksMapper {

    public int addBook(books model);

    public int updateBook(books model);

    public int deleteBook(int id);

    public List<books> queryBook(books model);
}

数据SQL语句的xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tushu.book.mapper.BooksMapper"><!--xxxMapper所在的包--!> <resultMap type="books" id="booksResult">
<id property="id" column="id"/>
<result property="title" column="title"/>
<result property="price" column="price"/>
<result property="publishDate" column="publishDate"/>
<!--<association property="dept" column="dept_id" javaType="SysDept" resultMap="deptResult" />-->
<!--<collection property="roles" javaType="java.util.List" resultMap="RoleResult" />-->
</resultMap> <!--<resultMap id="deptResult" type="SysDept">-->
<!--<id property="deptId" column="dept_id" />-->
<!--<result property="parentId" column="parent_id" />-->
<!--</resultMap>--> <!--<resultMap id="RoleResult" type="SysRole">-->
<!--<id property="roleId" column="role_id" />-->
<!--</resultMap>--> <select id="queryBook" parameterType="books" resultMap="booksResult">
select * from books where 1=1
<if test="title != null and title != ''">
AND title=#{title}
</if>
<if test="price != null and price >0 ">
AND price = #{price}
</if>
<if test="params.beginTime != null and params.beginTime != ''"><!-- 开始时间检索 -->
AND date_format(publishDate,'%y%m%d') &gt;= date_format(#{params.beginTime},'%y%m%d')
</if>
<if test="params.endTime != null and params.endTime != ''"><!-- 结束时间检索 -->
AND date_format(publishDate,'%y%m%d') &lt;= date_format(#{params.endTime},'%y%m%d')
</if>
<!-- 数据范围过滤 ${params.dataScope} --> </select> <delete id="deleteBook" parameterType="int">
delete from books where id = #{id}
</delete> <update id="updateBook" parameterType="books">
update books
<set>
<if test="title != null and title != ''">title = #{title},</if>
<if test="price != null and price >0 ">price = #{price},</if>
publishDate = sysdate()
</set>
where id = #{id}
</update> <insert id="addBook" parameterType="books" useGeneratedKeys="true" keyProperty="id">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
insert into books(
<if test="id != null and id > 0">id,</if>
<if test="title != null and title != '' ">title,</if>
<if test="price != null and price > 0 ">price,</if>
publishDate
)values(
<if test="id != null and id > 0">#{id},</if>
<if test="title != null and title != ''">#{title},</if>
<if test="price != null and price >0 ">#{price},</if>
sysdate()
)
</insert> </mapper>

然后是是ico的实现

接口

package com.tushu.book.service;

import com.tushu.book.domain.books;

import java.util.List;

public interface IBooksService {
public int addBook(books model); public int updateBook(books model); public int deleteBook(int id); public List<books> queryBook(books model);
}

实现类(逻辑),添加@Service注解和以接口名称+Impl结尾命名

package com.tushu.book.service.impl;

import com.tushu.book.domain.books;
import com.tushu.book.mapper.BooksMapper;
import com.tushu.book.service.IBooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; @Service
public class IBooksServiceImpl implements IBooksService {
@Autowired
private BooksMapper booksMapper; public int addBook(books model) {
return booksMapper.addBook(model);
} public int updateBook(books model) {
return booksMapper.updateBook(model);
} public int deleteBook(int id) {
return booksMapper.deleteBook(id);
} public List<books> queryBook(books model) {
return booksMapper.queryBook(model);
}
}

然后就是控制器的调用

package com.tushu.book.controller;

import com.tushu.book.domain.books;
import com.tushu.book.service.IBooksService;
import com.tushu.book.service.ITestDataService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import java.util.List; @Controller
@RequestMapping("/system/books")
public class bookscontroller {
private String prefix = "system/books";
@Autowired
IBooksService ibooksService;
@Autowired
ITestDataService testDataService; //页面
@RequiresPermissions("system:books:view")
@GetMapping()
public String books() {
return prefix;
}
//查询
@ResponseBody
@PostMapping("/query")
public List<books> querybook(@Validated books model){
List<books> data = ibooksService.queryBook(model);
return data;
}
//添加
@ResponseBody
@PostMapping("/add")
public books addBook(@Validated books model){
int id = ibooksService.addBook(model);
return model;
}
//修改
@ResponseBody
@PostMapping("/updatebook")
public boolean updatebook(@Validated books model){
int row = ibooksService.updateBook(model);
return row >= 0 ? true:false;
}
//删除
@ResponseBody
@GetMapping("/deletebook/{id}")
public boolean deletebook(@PathVariable("id") int id){
int row = ibooksService.deleteBook(id);
return row >= 0 ? true:false;
} @ResponseBody
@GetMapping("/speak/{str}")
public String speak(@PathVariable("str") String str){
return testDataService.speak(str);
} @ResponseBody
@RequestMapping("/getByName")
public String getByName(String name){
return "hi ,welcome to " + name;
}
}

springmvc+mybatis的增删改查入门的更多相关文章

  1. ssm 框架实现增删改查CRUD操作(Spring + SpringMVC + Mybatis 实现增删改查)

    ssm 框架实现增删改查 SpringBoot 项目整合 一.项目准备 1.1 ssm 框架环境搭建 1.2 项目结构图如下 1.3 数据表结构图如下 1.4 运行结果 二.项目实现 1. Emplo ...

  2. [NewLife.XCode]增删改查入门

    NewLife.XCode是一个有10多年历史的开源数据中间件,由新生命团队(2002~2019)开发完成并维护至今,以下简称XCode. 整个系列教程会大量结合示例代码和运行日志来进行深入分析,蕴含 ...

  3. 学习MyBatis必知必会(5)~了解myBatis的作用域和生命周期并抽取工具类MyBatisUtil、mybatis执行增删改查操作

    一.了解myBatis的作用域和生命周期[错误的使用会导致非常严重的并发问题] (1)SqlSessionFactoryBuilder [ 作用:仅仅是用来创建SqlSessionFactory,作用 ...

  4. Spring Boot入门系列(六)如何整合Mybatis实现增删改查

    前面介绍了Spring Boot 中的整合Thymeleaf前端html框架,同时也介绍了Thymeleaf 的用法.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/z ...

  5. springMVC操作mongoDB增删改查

    下面是mongoDb简单的增删改查(新闻类) 附:query.addCriteria(Criteria.where("modelId").ne("").ne(n ...

  6. MyBatis的增删改查。

    数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改,并且对程序接口做了一些调整,以及对一些问题进行了解答. 1.调整后的结构图: 2.连接数据库文件配置分离: 一般的程序都会把连 ...

  7. MyBatis批量增删改查操作

      前文我们介绍了MyBatis基本的增删该查操作,本文介绍批量的增删改查操作.前文地址:http://blog.csdn.net/mahoking/article/details/43673741 ...

  8. 上手spring boot项目(三)之spring boot整合mybatis进行增删改查的三种方式。

    1.引入依赖. <!--springboot的web起步依赖--><dependency> <groupId>org.springframework.boot< ...

  9. 上手spring boot项目(三)之spring boot整合mybatis进行增删改查

    使用mybatis框架进行增删改查大致有两种基础方式,一种扩展方式.两种基础方式分别是使用xml映射文件和使用方法注解.扩展方式是使用mybatis-plus的方式,其用法类似于spring-data ...

随机推荐

  1. leetcode 874. Walking Robot Simulation

    874. Walking Robot Simulation https://www.cnblogs.com/grandyang/p/10800993.html 每走一步(不是没走commands里的一 ...

  2. IDEA Git 修改后的文件无法Commit

    转自:https://blog.csdn.net/moneyshi/article/details/81298861 因对IDEA使用不熟,在使用和配置GIT的时候,可能哪里配置错误,导致我一直无法使 ...

  3. 如何解决Access操作或事件已被禁用模式阻止

    操作或事件已被禁用模式阻止.本来是Access安全设置的一部分,可以防止一些危险性的宏自动运行损坏数据,但是如果是自己在设计或是修改Access数据库的时候,这个就比较烦人了,一次次的提示,每次都需要 ...

  4. java连接数据库失败:java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

    说一下我的情况: 在测试环境中运行没有任何问题,但是导出war包之后,就将war包上传到线上服务器的webapps目录下,然后启动Tomcat,等待Tomcat将上传的war包解压(此时Tomcat没 ...

  5. pyenv、virtualenv、virtualenvwrapper三种python多版本介绍

    今天有把此前接触过的三种python实现多版本环境用到的软件pyenv.virtualenv.virtualenvwrapper,了解了一番,现做如下总结: 一.pyenv: 是针对python多版本 ...

  6. 使用HSQLDB 客户端(jvm自带数据库使用技巧)

    数据库连接jar包 http://how2j.cn/frontdownload?bean.id=1169 hsqldb.jarservlet-2_3-fcs-classfiles.zipsqltool ...

  7. Django中authenticate和login模块

    Django 提供内置的视图(view)函数用于处理登录和退出,Django提供两个函数来执行django.contrib.auth中的动作 : authenticate()和login(). 认证给 ...

  8. Flink 在IDEA执行时的webui

    不过Flink IDEA中执行的webui 需要 flink-runtime-web 包的支持 pom 如下: <dependency> <groupId>org.apache ...

  9. 编译安装hls协议切片工具 m3u8-segmenter

    操作系统:Ubuntu16.04.4 amd64 安装http://m3u8-segmenter.inodes.org/方式安装m3u8-segmenter报错,于是有了这篇文章 apt instal ...

  10. Python - Django - 模板语言之 Tags(标签)

    标签使用 {% %} 注释语句:{# #} for 循环: views.py: from django.shortcuts import render, redirect, HttpResponse ...