spring boot mybatis 整合教程

本项目使用的环境:

  • 开发工具:Intellij IDEA 2017.1.3
  • springboot: 1.5.6
  • jdk:1.8.0_161
  • maven:3.3.9

额外功能

  • PageHelper 分页插件
  • mybatis generator 自动生成代码插件

步骤:

1. 创建一个springboot项目:

spring boot mybatis 整合教程

2. 创建项目的文件结构以及jdk的版本

spring boot mybatis 整合教程

3. 选择项目所需要的依赖

spring boot mybatis 整合教程

spring boot mybatis 整合教程

然后点击finish

4. 看一下文件的结构:

spring boot mybatis 整合教程

5. 查看一下pom.xml:

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4     <modelVersion>4.0.0</modelVersion>
  5 
  6     <groupId>com.winter</groupId>
  7     <artifactId>springboot-mybatis-demo</artifactId>
  8     <version>0.0.1-SNAPSHOT</version>
  9     <packaging>jar</packaging>
 10 
 11     <name>springboot-mybatis-demo</name>
 12     <description>Demo project for Spring Boot</description>
 13 
 14     <parent>
 15         <groupId>org.springframework.boot</groupId>
 16         <artifactId>spring-boot-starter-parent</artifactId>
 17         <version>1.5.6.RELEASE</version>
 18         <relativePath/> <!-- lookup parent from repository -->
 19     </parent>
 20 
 21     <properties>
 22         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 23         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 24         <java.version>1.7</java.version>
 25     </properties>
 26 
 27     <dependencies>
 28         <dependency>
 29             <groupId>org.mybatis.spring.boot</groupId>
 30             <artifactId>mybatis-spring-boot-starter</artifactId>
 31             <version>1.3.0</version>
 32         </dependency>
 33         <dependency>
 34             <groupId>org.springframework.boot</groupId>
 35             <artifactId>spring-boot-starter-thymeleaf</artifactId>
 36         </dependency>
 37         <dependency>
 38             <groupId>org.springframework.boot</groupId>
 39             <artifactId>spring-boot-starter-web</artifactId>
 40         </dependency>
 41 
 42         <dependency>
 43             <groupId>org.springframework.boot</groupId>
 44             <artifactId>spring-boot-starter-test</artifactId>
 45             <scope>test</scope>
 46         </dependency>
 47         <dependency>
 48             <groupId>mysql</groupId>
 49             <artifactId>mysql-connector-java</artifactId>
 50             <version>5.1.35</version>
 51         </dependency>
 52         
 53     
 54         <dependency>
 55             <groupId>com.fasterxml.jackson.core</groupId>
 56             <artifactId>jackson-core</artifactId>
 57         </dependency>
 58         <dependency>
 59             <groupId>com.fasterxml.jackson.core</groupId>
 60             <artifactId>jackson-databind</artifactId>
 61         </dependency>
 62         <dependency>
 63             <groupId>com.fasterxml.jackson.datatype</groupId>
 64             <artifactId>jackson-datatype-joda</artifactId>
 65         </dependency>
 66         <dependency>
 67             <groupId>com.fasterxml.jackson.module</groupId>
 68             <artifactId>jackson-module-parameter-names</artifactId>
 69         </dependency>
 70         <!-- 分页插件 -->
 71         <dependency>
 72             <groupId>com.github.pagehelper</groupId>
 73             <artifactId>pagehelper-spring-boot-starter</artifactId>
 74             <version>1.1.2</version>
 75         </dependency>
 76         <!-- alibaba的druid数据库连接池 -->
 77         <dependency>
 78             <groupId>com.alibaba</groupId>
 79             <artifactId>druid-spring-boot-starter</artifactId>
 80             <version>1.1.0</version>
 81         </dependency>
 82     </dependencies>
 83 
 84     <build>
 85         <plugins>
 86             <plugin>
 87                 <groupId>org.springframework.boot</groupId>
 88                 <artifactId>spring-boot-maven-plugin</artifactId>
 89             </plugin>
 90             <!-- mybatis generator 自动生成代码插件 -->
 91             <plugin>
 92                 <groupId>org.mybatis.generator</groupId>
 93                 <artifactId>mybatis-generator-maven-plugin</artifactId>
 94                 <version>1.3.2</version>
 95                 <configuration>
 96                     <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
 97                     <overwrite>true</overwrite>
 98                     <verbose>true</verbose>
 99                 </configuration>
100             </plugin>
101         </plugins>
102     </build>
103 
104 
105 </project>

6. 项目不使用application.properties文件 而使用更加简洁的application.yml文件:

将原有的resource文件夹下的application.properties文件删除,创建一个新的application.yml配置文件,

文件的内容如下:

 1 server:
 2   port: 8080
 3 
 4 spring:
 5     datasource:
 6         name: test
 7         url: jdbc:mysql://127.0.0.1:3306/depot
 8         username: root
 9         password: root
10         # 使用druid数据源
11         type: com.alibaba.druid.pool.DruidDataSource
12         driver-class-name: com.mysql.jdbc.Driver
13         filters: stat
14         maxActive: 20
15         initialSize: 1
16         maxWait: 60000
17         minIdle: 1
18         timeBetweenEvictionRunsMillis: 60000
19         minEvictableIdleTimeMillis: 300000
20         validationQuery: select 'x'
21         testWhileIdle: true
22         testOnBorrow: false
23         testOnReturn: false
24         poolPreparedStatements: true
25         maxOpenPreparedStatements: 20
26 
27 ## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别
28 mybatis:
29   mapper-locations: classpath:mapping/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
30   type-aliases-package: com.winter.model  # 注意:对应实体类的路径
31 
32 #pagehelper分页插件
33 pagehelper:
34     helperDialect: mysql
35     reasonable: true
36     supportMethodsArguments: true
37     params: count=countSql

7. 创建数据库:

1 CREATE DATABASE mytest;
2 
3 CREATE TABLE t_user(
4   user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
5   user_name VARCHAR(255) NOT NULL ,
6   password VARCHAR(255) NOT NULL ,
7   phone VARCHAR(255) NOT NULL
8 ) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;

8. 使用mybatis generator 自动生成代码:

  • 配置pom.xml中generator 插件所对应的配置文件 ${basedir}/src/main/resources/generator/generatorConfig.xml
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE generatorConfiguration
 3         PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
 4         "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
 5 <generatorConfiguration>
 6     <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
 7     <classPathEntry  location="E:\developer\mybatis-generator-core-1.3.2\lib\mysql-connector-java-5.1.25-bin.jar"/>
 8     <context id="DB2Tables"  targetRuntime="MyBatis3">
 9         <commentGenerator>
10             <property name="suppressDate" value="true"/>
11             <!-- 是否去除自动生成的注释 true:是 : false:否 -->
12             <property name="suppressAllComments" value="true"/>
13         </commentGenerator>
14         <!--数据库链接URL,用户名、密码 -->
15         <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/mytest" userId="root" password="root">
16         </jdbcConnection>
17         <javaTypeResolver>
18             <property name="forceBigDecimals" value="false"/>
19         </javaTypeResolver>
20         <!-- 生成模型的包名和位置-->
21         <javaModelGenerator targetPackage="com.winter.model" targetProject="src/main/java">
22             <property name="enableSubPackages" value="true"/>
23             <property name="trimStrings" value="true"/>
24         </javaModelGenerator>
25         <!-- 生成映射文件的包名和位置-->
26         <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
27             <property name="enableSubPackages" value="true"/>
28         </sqlMapGenerator>
29         <!-- 生成DAO的包名和位置-->
30         <javaClientGenerator type="XMLMAPPER" targetPackage="com.winter.mapper" targetProject="src/main/java">
31             <property name="enableSubPackages" value="true"/>
32         </javaClientGenerator>
33         <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
34         <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
35     </context>
36 </generatorConfiguration>
  • 点击run-Edit Configurations

spring boot mybatis 整合教程

  • 添加配置

spring boot mybatis 整合教程

  • 运行

注意!!!同一张表一定不要运行多次,因为mapper的映射文件中会生成多次的代码,导致报错,切记

spring boot mybatis 整合教程

最后生成的文件以及结构:

spring boot mybatis 整合教程

9. 生成的文件

UserMapper.java

 1 package com.winter.mapper;
 2 
 3 import com.winter.model.User;
 4 
 5 public interface UserMapper {
 6     int deleteByPrimaryKey(Integer userId);
 7 
 8     int insert(User record);
 9 
10     int insertSelective(User record);
11 
12     User selectByPrimaryKey(Integer userId);
13 
14     int updateByPrimaryKeySelective(User record);
15 
16     int updateByPrimaryKey(User record);
17     //这个方式我自己加的
18     List<User> selectAllUser();
19 }

User.java

 1 package com.winter.model;
 2 
 3 public class User {
 4     private Integer userId;
 5 
 6     private String userName;
 7 
 8     private String password;
 9 
10     private String phone;
11 
12     public Integer getUserId() {
13         return userId;
14     }
15 
16     public void setUserId(Integer userId) {
17         this.userId = userId;
18     }
19 
20     public String getUserName() {
21         return userName;
22     }
23 
24     public void setUserName(String userName) {
25         this.userName = userName == null ? null : userName.trim();
26     }
27 
28     public String getPassword() {
29         return password;
30     }
31 
32     public void setPassword(String password) {
33         this.password = password == null ? null : password.trim();
34     }
35 
36     public String getPhone() {
37         return phone;
38     }
39 
40     public void setPhone(String phone) {
41         this.phone = phone == null ? null : phone.trim();
42     }
43 }

对于sql语句这种黄色的背景,真心是看不下去了(解决方案):

spring boot mybatis 整合教程

**UserMapper.xml **

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 3 <mapper namespace="com.winter.mapper.UserMapper" >
 4   <resultMap id="BaseResultMap" type="com.winter.model.User" >
 5     <id column="user_id" property="userId" jdbcType="INTEGER" />
 6     <result column="user_name" property="userName" jdbcType="VARCHAR" />
 7     <result column="password" property="password" jdbcType="VARCHAR" />
 8     <result column="phone" property="phone" jdbcType="VARCHAR" />
 9   </resultMap>
10   <sql id="Base_Column_List" >
11     user_id, user_name, password, phone
12   </sql>
13   <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
14     select 
15     <include refid="Base_Column_List" />
16     from t_user
17     where user_id = #{userId,jdbcType=INTEGER}
18   </select>
19   <!-- 这个方法是我自己加的 -->
20   <select id="selectAllUser" resultMap="BaseResultMap">
21     select
22     <include refid="Base_Column_List" />
23     from t_user
24   </select>
25   <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
26     delete from t_user
27     where user_id = #{userId,jdbcType=INTEGER}
28   </delete>
29   <insert id="insert" parameterType="com.winter.model.User" >
30     insert into t_user (user_id, user_name, password, 
31       phone)
32     values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
33       #{phone,jdbcType=VARCHAR})
34   </insert>
35   <insert id="insertSelective" parameterType="com.winter.model.User" >
36     insert into t_user
37     <trim prefix="(" suffix=")" suffixOverrides="," >
38       <if test="userId != null" >
39         user_id,
40       </if>
41       <if test="userName != null" >
42         user_name,
43       </if>
44       <if test="password != null" >
45         password,
46       </if>
47       <if test="phone != null" >
48         phone,
49       </if>
50     </trim>
51     <trim prefix="values (" suffix=")" suffixOverrides="," >
52       <if test="userId != null" >
53         #{userId,jdbcType=INTEGER},
54       </if>
55       <if test="userName != null" >
56         #{userName,jdbcType=VARCHAR},
57       </if>
58       <if test="password != null" >
59         #{password,jdbcType=VARCHAR},
60       </if>
61       <if test="phone != null" >
62         #{phone,jdbcType=VARCHAR},
63       </if>
64     </trim>
65   </insert>
66   <update id="updateByPrimaryKeySelective" parameterType="com.winter.model.User" >
67     update t_user
68     <set >
69       <if test="userName != null" >
70         user_name = #{userName,jdbcType=VARCHAR},
71       </if>
72       <if test="password != null" >
73         password = #{password,jdbcType=VARCHAR},
74       </if>
75       <if test="phone != null" >
76         phone = #{phone,jdbcType=VARCHAR},
77       </if>
78     </set>
79     where user_id = #{userId,jdbcType=INTEGER}
80   </update>
81   <update id="updateByPrimaryKey" parameterType="com.winter.model.User" >
82     update t_user
83     set user_name = #{userName,jdbcType=VARCHAR},
84       password = #{password,jdbcType=VARCHAR},
85       phone = #{phone,jdbcType=VARCHAR}
86     where user_id = #{userId,jdbcType=INTEGER}
87   </update>
88 </mapper>

10. 打开类SpringbootMybatisDemoApplication.java,这个是springboot的启动类。我们需要添加点东西:

 1 package com.winter;
 2 
 3 import org.mybatis.spring.annotation.MapperScan;
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6 
 7 @SpringBootApplication
 8 @MapperScan("com.winter.mapper")//将项目中对应的mapper类的路径加进来就可以了
 9 public class SpringbootMybatisDemoApplication {
10 
11     public static void main(String[] args) {
12         SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
13     }
14 }

注意:@MapperScan("com.winter.mapper")这个注解非常的关键,这个对应了项目中mapper(dao)所对应的包路径,很多同学就是这里忘了加导致异常的

11. 到这里所有的搭建工作都完成了,接下来就是测试的工作,没使用junit4进行测试:

首先看一下完成之后的文件的结构:

spring boot mybatis 整合教程

现在controller,service层的代码都写好:

UserController.java

 1 package com.winter.Controller;
 2 
 3 import com.winter.model.User;
 4 import com.winter.service.UserService;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.PathVariable;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.ResponseBody;
10 
11 /**
12  * Created by Administrator on 2017/8/16.
13  */
14 @Controller
15 @RequestMapping(value = "/user")
16 public class UserController {
17 
18     @Autowired
19     private UserService userService;
20 
21     @ResponseBody
22     @RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
23     public int addUser(User user){
24         return userService.addUser(user);
25     }
26 
27     @ResponseBody
28     @RequestMapping(value = "/all/{pageNum}/{pageSize}", produces = {"application/json;charset=UTF-8"})
29     public Object findAllUser(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){
30         
31         return userService.findAllUser(pageNum,pageSize);
32     }
33 }

UserService.java

 1 package com.winter.service;
 2 
 3 import com.winter.model.User;
 4 
 5 import java.util.List;
 6 
 7 /**
 8  * Created by Administrator on 2017/8/16.
 9  */
10 public interface UserService {
11 
12     int addUser(User user);
13 
14     List<User> findAllUser(int pageNum, int pageSize);
15 }

UserServiceImpl.java

 1 package com.winter.service.impl;
 2 
 3 import com.github.pagehelper.PageHelper;
 4 import com.winter.mapper.UserMapper;
 5 import com.winter.model.User;
 6 import com.winter.service.UserService;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.stereotype.Service;
 9 
10 import java.util.List;
11 
12 /**
13  * Created by Administrator on 2017/8/16.
14  */
15 @Service(value = "userService")
16 public class UserServiceImpl implements UserService {
17 
18     @Autowired
19     private UserMapper userMapper;//这里会报错,但是并不会影响
20 
21     @Override
22     public int addUser(User user) {
23 
24         return userMapper.insertSelective(user);
25     }
26 
27     /*
28     * 这个方法中用到了我们开头配置依赖的分页插件pagehelper
29     * 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可;
30     * pageNum 开始页数
31     * pageSize 每页显示的数据条数
32     * */
33     @Override
34     public List<User> findAllUser(int pageNum, int pageSize) {
35         //将参数传给这个方法就可以实现物理分页了,非常简单。
36         PageHelper.startPage(pageNum, pageSize);
37         return userMapper.selectAllUser();
38     }
39 }

如果强迫症看不下去那个报错:(解决方法)

spring boot mybatis 整合教程

测试我使用了idea一个很用心的功能。

可以发http请求的插件

spring boot mybatis 整合教程

spring boot mybatis 整合教程

点击左侧的运行按钮就可以发送请求了;

如果返回值正确 说明你已经搭建成功了!!

ps:如果出现mapper注入不了的情况,请检查版本,当前博客的搭建方法只适合1.5.*版本的。

上一篇:枚举enum,通过key获取value,通过value获取key


下一篇:SQL 优化极简法则,还有谁不会?