Spring boot 学习:整合Mybatis

Posted sl-document

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring boot 学习:整合Mybatis相关的知识,希望对你有一定的参考价值。

  这篇博客是为后期使用在Springboot中使用shrio做基础准备的。原因是在之前练习Springboot整合shiro时,发现对mybatis的配置上理解不是很好,所以想整理一下,巩固自己对其理解。

  首先做一些准备工作,把数据库的表和数据准备一下:

数据库准备

技术分享图片
 1 -- ----------------------------
 2 -- Table structure for user
 3 -- ----------------------------
 4 DROP TABLE IF EXISTS `user`;
 5 CREATE TABLE `user`  (
 6   `id` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘ID‘,
 7   `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘姓名‘,
 8   `age` int(11) NULL DEFAULT NULL COMMENT ‘年龄‘,
 9   `sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘性别‘,
10   `address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘地址‘,
11   PRIMARY KEY (`id`) USING BTREE
12 ) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
13 
14 -- ----------------------------
15 -- Records of user
16 -- ----------------------------
17 INSERT INTO `user` VALUES (1, ‘小明‘, 18, ‘male‘, ‘江苏‘);
18 INSERT INTO `user` VALUES (2, ‘小红‘, 17, ‘female‘, ‘浙江‘);
19 INSERT INTO `user` VALUES (3, ‘小刘‘, 22, ‘female‘, ‘上海‘);
20 INSERT INTO `user` VALUES (4, ‘张三‘, 25, ‘male‘, ‘北京‘);
21 INSERT INTO `user` VALUES (5, ‘李四‘, 16, ‘female‘, ‘天津‘);
22 INSERT INTO `user` VALUES (6, ‘王五‘, 20, ‘female‘, ‘河北‘);
23 INSERT INTO `user` VALUES (7, ‘赵六‘, 21, ‘male‘, ‘四川‘);
24 INSERT INTO `user` VALUES (8, ‘田七‘, 28, ‘female‘, ‘重庆‘);
25 INSERT INTO `user` VALUES (9, ‘王二‘, 24, ‘male‘, ‘北京‘);
26 INSERT INTO `user` VALUES (10, ‘小波‘, 24, ‘male‘, ‘北京‘);
View Code

  pom.xml

然后新建一个spring boot项目(打包方式war),并在它的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.mine.test</groupId>
 7     <artifactId>springboot-mybatis</artifactId>
 8     <version>0.0.1-SNAPSHOT</version>
 9     <packaging>war</packaging>
10 
11     <name>springboot-mybatis</name>
12     <description>Springboot整合 mybatis练习案例</description>
13 
14     <parent>
15         <groupId>org.springframework.boot</groupId>
16         <artifactId>spring-boot-starter-parent</artifactId>
17         <version>1.5.9.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.8</java.version>
25     </properties>
26 
27     <dependencies>
28         <dependency>
29             <groupId>org.springframework.boot</groupId>
30             <artifactId>spring-boot-starter</artifactId>
31         </dependency>
32 
33         <dependency>
34             <groupId>org.springframework.boot</groupId>
35             <artifactId>spring-boot-starter-test</artifactId>
36             <scope>test</scope>
37         </dependency>
38         <dependency>
39             <groupId>org.springframework.boot</groupId>
40             <artifactId>spring-boot-starter-web</artifactId>
41         </dependency>
42         <!-- 数据库驱动 -->
43         <dependency>
44             <groupId>mysql</groupId>
45             <artifactId>mysql-connector-java</artifactId>
46         </dependency>
47         <!-- mybatis支持 -->
48         <dependency>
49             <groupId>org.mybatis.spring.boot</groupId>
50             <artifactId>mybatis-spring-boot-starter</artifactId>
51             <version>1.3.0</version>
52         </dependency>
53         <!--pagehelper -->
54         <dependency>
55             <groupId>com.github.pagehelper</groupId>
56             <artifactId>pagehelper-spring-boot-starter</artifactId>
57             <version>1.2.0</version>
58         </dependency>
59         <dependency>
60             <groupId>com.alibaba</groupId>
61             <artifactId>fastjson</artifactId>
62             <version>1.2.45</version>
63         </dependency>
64         <!-- 数据库连接池 -->
65         <dependency>
66             <groupId>com.alibaba</groupId>
67             <artifactId>druid</artifactId>
68             <version>1.0.14</version>
69         </dependency>
70         <dependency>
71             <groupId>org.springframework</groupId>
72             <artifactId>spring-expression</artifactId>
73         </dependency>
74     </dependencies>
75 
76     <build>
77         <plugins>
78             <plugin>
79                 <groupId>org.springframework.boot</groupId>
80                 <artifactId>spring-boot-maven-plugin</artifactId>
81             </plugin>
82         </plugins>
83     </build>
84 
85 </project>
View Code

  application.properties

依赖添加完之后,要为项目添加一下环境配置,每一项功能作用都在代码properties中做了注释 

技术分享图片
 1 # 端口设置
 2 server.port=8080
 3 # 数据源配置
 4 spring.datasource.url=jdbc:mysql://localhost:3306/mine_test
 5 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
 6 spring.datasource.username=root
 7 spring.datasource.password=root
 8 #连接池配置
 9 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
10 
11 #mybatis
12 #entity扫描的包名
13 mybatis.type-aliases-package=com.mine.test.domain
14 #Mapper.xml所在的位置
15 mybatis.mapper-locations=classpath*:/mybatis/*Mapper.xml
16 # mybatis其他配置
17 #mybatis.config-location=mybatis-config.xml配置文件的路径
18 #mybatis.type-handlers-package=扫描typeHandlers的包
19 #mybatis.check-config-location=检查配置文件是否存在
20 #mybatis.executor-type=设置执行模式(SIMPLE, REUSE, BATCH),默认为SIMPLE
21 
22 #pagehelper分页插件配置
23 pagehelper.helperDialect=mysql
24 pagehelper.reasonable=true
25 pagehelper.supportMethodsArguments=true
26 pagehelper.params=count=countSql
27 
28 #日志配置
29 #logging.level.com.xiaolyuh=debug
30 logging.level.org.springframework.web=debug
31 logging.level.org.springframework.transaction=debug
32 logging.level.org.mybatis=debug
33 
34 debug=false
View Code

  实体类User

接下来创建与数据库对应的实体类 

技术分享图片
 1 package com.mine.test.domain;
 2 /**
 3  * 
 4  * @Title: User.java 
 5  * @Prject: springboot-mybatis
 6  * @Package: com.mine.test.domain 
 7  * @Description: 测试实体类
 8  * @author: mine   
 9  * @date: 2018年2月6日 下午4:37:05 
10  * @version: V1.0
11  */
12 public class User {
13     
14     /**
15      *  id
16      */
17     private Integer id;
18     /**
19      *  姓名
20      */
21     private String name;
22     /**
23      *  年龄
24      */
25     private Integer age;
26     /**
27      *  性别
28      */
29     private String sex;
30     /**
31      *  地址
32      */
33     private String address;
34     
35     public Integer getId() {
36         return id;
37     }
38     public void setId(Integer id) {
39         this.id = id;
40     }
41     public String getName() {
42         return name;
43     }
44     public Integer getAge() {
45         return age;
46     }
47     public void setAge(Integer age) {
48         this.age = age;
49     }
50     public void setName(String name) {
51         this.name = name;
52     }
53     public String getSex() {
54         return sex;
55     }
56     public void setSex(String sex) {
57         this.sex = sex;
58     }
59     public String getAddress() {
60         return address;
61     }
62     public void setAddress(String address) {
63         this.address = address;
64     }
65     
66     @Override
67     public String toString() {
68         return "User [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + ", address=" + address + "]";
69     }
70     
71 }
View Code

  分页查询使用UserPageQuery

我的这个小栗子中,还添加了pagehelper的支持,所以这里还写了一个针对多条件分页查询的queryVo类,(筛选条件有:name,sex,address)

技术分享图片
 1 package com.mine.test.domain.queryVo;
 2 
 3 import com.mine.test.domain.User;
 4 /**
 5  * 
 6  * @Title: UserPageQuery.java 
 7  * @Prject: springboot-mybatis
 8  * @Package: com.mine.test.domain.queryVo 
 9  * @Description: 用于对User的多条件分页查询
10  * @author: mine   
11  * @date: 2018年2月7日 下午5:21:04 
12  * @version: V1.0
13  */
14 public class UserPageQuery extends User {
15 
16     /**
17      * 当前页
18      */
19     private Integer pageNum;
20     /**
21      * 每页查询记录数
22      */
23     private Integer pageSize;
24 
25     public Integer getPageNum() {
26         return pageNum;
27     }
28 
29     public void setPageNum(Integer pageNum) {
30         this.pageNum = pageNum;
31     }
32 
33     public Integer getPageSize() {
34         return pageSize;
35     }
36 
37     public void setPageSize(Integer pageSize) {
38         this.pageSize = pageSize;
39     }
40     
41 }
View Code

   mybatis的接口和xml

持久层UserDao

技术分享图片
 1 package com.mine.test.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.mine.test.domain.User;
 6 import com.mine.test.domain.queryVo.UserPageQuery;
 7 /**
 8  * 
 9  * @Title: UserDao.java 
10  * @Prject: springboot-mybatis
11  * @Package: com.mine.test.dao 
12  * @Description: 持久层
13  * @author: mine   
14  * @date: 2018年2月7日 下午5:23:22 
15  * @version: V1.0
16  */
17 public interface UserDao {
18 
19     User getUserById(Integer id);
20 
21     List<User> queryList(UserPageQuery user);
22 
23 }
View Code

  持久层接口对应的Mapper.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.mine.test.dao.UserDao">
 4     <resultMap id="BaseResultMap" type="com.mine.test.domain.User">
 5         <id column="id" property="id" jdbcType="INTEGER" />
 6         <result column="name" property="name" jdbcType="VARCHAR" />
 7         <result column="sex" property="sex" jdbcType="VARCHAR" />
 8         <result column="address" property="address" jdbcType="VARCHAR" />
 9     </resultMap>
10     <sql id="Base_Column_List">
11         id, name, age, sex, address
12     </sql>
13 
14     <!-- 根据ID获取 -->
15     <select id="getUserById" resultMap="BaseResultMap" parameterType="java.lang.Integer">
16         select
17         <include refid="Base_Column_List" />
18         from user
19         where id = #{id,jdbcType=INTEGER}
20     </select>
21     
22     <!-- 分页多条件获取 -->
23     <select id="queryList" resultMap="BaseResultMap" parameterType="com.mine.test.domain.queryVo.UserPageQuery">
24         SELECT
25             <include refid="Base_Column_List" />
26         FROM
27             `user` 
28         <where>
29             <if test="name != null and name != ‘‘">
30                 `name` LIKE CONCAT(‘%‘, #{name}, ‘%‘)
31             </if>
32             <if test="sex != null and sex != ‘‘">
33                 AND sex LIKE #{sex}
34             </if>
35             <if test="address != null and address != ‘‘">
36                 AND address LIKE CONCAT(‘%‘, #{address}, ‘%‘)
37             </if>
38         </where>
39     </select>
40     
41 </mapper>
View Code

  业务层接口UserService

技术分享图片
 1 package com.mine.test.service;
 2 
 3 import com.github.pagehelper.PageInfo;
 4 import com.mine.test.domain.User;
 5 import com.mine.test.domain.queryVo.UserPageQuery;
 6 /**
 7  * 
 8  * @Title: UserService.java 
 9  * @Prject: springboot-mybatis
10  * @Package: com.mine.test.service 
11  * @Description: service接口
12  * @author: mine   
13  * @date: 2018年2月7日 下午5:22:36 
14  * @version: V1.0
15  */
16 public interface UserService {
17 
18     User getUserById(Integer id);
19 
20     PageInfo<User> queryList(UserPageQuery user);
21 
22 }
View Code

  业务层接口实现类UserServiceImpl

技术分享图片
 1 package com.mine.test.service.impl;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Service;
 7 
 8 import com.github.pagehelper.PageHelper;
 9 import com.github.pagehelper.PageInfo;
10 import com.mine.test.dao.UserDao;
11 import com.mine.test.domain.User;
12 import com.mine.test.domain.queryVo.UserPageQuery;
13 import com.mine.test.service.UserService;
14 /**
15  * 
16  * @Title: UserServiceImpl.java 
17  * @Prject: springboot-mybatis
18  * @Package: com.mine.test.service.impl 
19  * @Description: service实现类
20  * @author: mine   
21  * @date: 2018年2月7日 下午5:22:59 
22  * @version: V1.0
23  */
24 @Service("userService")
25 public class UserServiceImpl implements UserService {
26     
27     @Autowired
28     private UserDao userDao;
29 
30     @Override
31     public User getUserById(Integer id) {
32         return userDao.getUserById(id);
33     }
34 
35     @Override
36     public PageInfo<User> queryList(UserPageQuery user) {
37         PageHelper.startPage(user.getPageNum(), user.getPageSize());
38         PageHelper.orderBy("age DESC");
39         List<User> users = userDao.queryList(user);
40         return new PageInfo<>(users);
41     }
42 
43 }
View Code

  控制层UserController

有两个接口,一个是根据User的id获取User信息,只要接受Integer类型的id就可以查询了。另一个是对User进行多条件分页查询的接口,用的针对这个接口的queryVo类UserPageQuery,除基本的筛选信息外,还增加了分页查询需要的两个属性pageNum,pageSize.

技术分享图片
 1 package com.mine.test.controller;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.springframework.web.bind.annotation.PathVariable;
 6 import org.springframework.web.bind.annotation.RequestBody;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RequestMethod;
 9 import org.springframework.web.bind.annotation.RestController;
10 
11 import com.github.pagehelper.PageInfo;
12 import com.mine.test.domain.User;
13 import com.mine.test.domain.queryVo.UserPageQuery;
14 import com.mine.test.service.UserService;
15 /**
16  * 
17  * @Title: UserController.java 
18  * @Prject: springboot-mybatis
19  * @Package: com.mine.test.controller 
20  * @Description: 控制层
21  * @author: mine   
22  * @date: 2018年2月7日 下午5:28:07 
23  * @version: V1.0
24  */
25 @RestController
26 @RequestMapping("/user")
27 public class UserController {
28     
29     @Resource(name = "userService")
30     private UserService userService;
31     
32     /**
33      * 
34      * @Title: getUserById 
35      * @Description: 根据User的id获取User信息
36      * @param @param id
37      * @param @return
38      * @param @throws Exception    参数列表
39      * @return User    返回类型 
40      * @throws
41      */
42     @RequestMapping(value = "/getUserById/{id}", method = RequestMethod.POST)
43     public User getUserById(@PathVariable(name = "id", required = true) Integer id) throws Exception {
44         if (null == id) {
45             throw new Exception("id不能为空");
46         }
47         User user = userService.getUserById(id);
48         if (null == user) {
49             throw new Exception("user不存在");
50         }
51         return user;
52     }
53     
54     /**
55      * 
56      * @Title: queryList 
57      * @Description: 对User的多条件分页查询 
58      * @param @param userPageQuery    针对多条件分页查询的一个queryVo类
59      * @param @return
60      * @param @throws Exception    参数列表
61      * @return PageInfo<User>    返回类型 
62      * @throws
63      */
64     @RequestMapping(value = "/queryList", method = RequestMethod.POST)
65     public PageInfo<User> queryList(@RequestBody UserPageQuery userPageQuery) throws Exception {
66         PageInfo<User> pageBean = userService.queryList(userPageQuery);
67         return pageBean;
68     }
69 }
View Code

  项目启动类Application

Appliaction中的@MapperScan这个注解是不能漏掉的,这个注解里面填入Dao层包路径后,会自动的去扫描其中的接口;

或者,不想写这个@MapperScan的话,也可以在每一个接口的上面写上@Mapper这个注解

技术分享图片
 1 package com.mine;
 2 
 3 import org.mybatis.spring.annotation.MapperScan;
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6 /**
 7  * 
 8  * @Title: Application.java 
 9  * @Prject: springboot-mybatis
10  * @Package: com.mine 
11  * @Description: 项目启动类
12  * @author: mine   
13  * @date: 2018年2月7日 下午5:30:44 
14  * @version: V1.0
15  */
16 @SpringBootApplication
17 @MapperScan("com.mine.test.dao")
18 public class Application {
19 
20     public static void main(String[] args) {
21         // @MapperScan这个注解是用来扫描Dao层接口的,需要填入接口包路径
22         SpringApplication.run(Application.class, args);
23     }
24 }
View Code

   代码都写完之后,右击Application启动项目,使用postman测试一下代码

  测试路径:

  技术分享图片

  查询结果:

  

1 {
2     "id": 1,
3     "name": "小明",
4     "age": 18,
5     "sex": "male",
6     "address": "江苏"
7 }

 

  接下来,再做一下对多条件分页查询的接口测试

  测试路径:

  技术分享图片

  测试参数:

1 {
2     "pageNum" : 1,
3     "pageSize" : 3,
4     "sex" : "female"
5 }

  测试结果:

 1 {
 2     "pageNum": 1,
 3     "pageSize": 3,
 4     "size": 3,
 5     "startRow": 1,
 6     "endRow": 3,
 7     "total": 5,
 8     "pages": 2,
 9     "list": [
10         {
11             "id": 8,
12             "name": "田七",
13             "age": 28,
14             "sex": "female",
15             "address": "重庆"
16         },
17         {
18             "id": 3,
19             "name": "小刘",
20             "age": 22,
21             "sex": "female",
22             "address": "上海"
23         },
24         {
25             "id": 6,
26             "name": "王五",
27             "age": 20,
28             "sex": "female",
29             "address": "河北"
30         }
31     ],
32     "prePage": 0,
33     "nextPage": 2,
34     "isFirstPage": true,
35     "isLastPage": false,
36     "hasPreviousPage": false,
37     "hasNextPage": true,
38     "navigatePages": 8,
39     "navigatepageNums": [
40         1,
41         2
42     ],
43     "navigateFirstPage": 1,
44     "navigateLastPage": 2,
45     "firstPage": 1,
46     "lastPage": 2
47 }

  测试下来,运行正常。

  这里面最主要的应该是application.properties文件里对mybatis的Mapper.xml路径扫描的设置,以及启动类中对Dao层接口的@MapperScan的注解设置,只要这两个配置都正确,就能够正常的去使用它了。

 

以上是关于Spring boot 学习:整合Mybatis的主要内容,如果未能解决你的问题,请参考以下文章

Spring boot 学习:整合Mybatis

Spring Boot整合MyBatis学习总结

spring boot 学习之路3( 集成mybatis )

SpringBoot 学习笔记 -- [spring Boot集成阿里Druid数据源,整合Mybatis搭建一个案例试试]

spring boot整合mybatis

SpringBoot学习笔记:整合mybatis