SpringBoot 集成 Mybatis 操作数据库

SpringBoot 集成 Mybatis 操作数据库

文章目录

  !版权声明:本博客内容均为原创,每篇博文作为知识积累,写博不易,转载请注明出处。


系统环境:

  • JDK 版本:1.8
  • 数据库:Mysql 8.0
  • Mybatis 版本:3.5.4
  • SpringBoot 版本:2.2.5.RELEASE

参考地址:

示例项目地址:

一、Mybatis 简介

       MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

这里主要是介绍下如果通过 xml 方式来使用 Mybatis,这种方式比较灵活,尤其是在写复杂 SQL 语句时,能很好的创建表与表之前的关系,如果是单表方式,更推荐使用 mybatis-plus 或者 jpa

二、示例准备

2.1 表结构

所有表都是用于方便演示,请不要在乎合理性。

总共拥有 group(用户组表)、 user(用户表) 、 role(角色表)、user_role(用户角色关系表)、base_info(用户基本信息表)五个表。

用户组表 group:

用户组表是对用户进行分组归类,该表内容如下:

用户表 user:

用户表是用于记录 用户名密码 等用户基本信息,该表内容如下:

角色表 role:

角色表是记录角色信息,用于与用户绑定,一个用户可能拥有多个角色,一个角色也可能属于多个用户,该表内容如下:

用户角色关系表:

用户关系表是用于维护 用户表角色表 两表间的关联关系,该表内容如下:

用户基本信息表 base_info:

用户基本信息表是用于记录用户 姓名性别生日备注信息 等,该表内容如下:

2.2 表 SQL

Mysql 的表 SQL 文件内容如下:

  1SET NAMES utf8mb4;
  2SET FOREIGN_KEY_CHECKS = 0;
  3
  4-- ----------------------------
  5-- Table structure for base_info
  6-- ----------------------------
  7DROP TABLE IF EXISTS `base_info`;
  8CREATE TABLE `base_info`  (
  9  `id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
 10  `user_id` int(0) NULL DEFAULT NULL COMMENT '用户ID号',
 11  `name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '姓名',
 12  `sex` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '性别',
 13  `birthday` date NULL DEFAULT NULL COMMENT '生日',
 14  `remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '备注',
 15  PRIMARY KEY (`id`) USING BTREE
 16) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;
 17
 18-- ----------------------------
 19-- Records of base_info
 20-- ----------------------------
 21INSERT INTO `base_info` VALUES (1, 1, '张三', '男', '1994-08-01', '无');
 22INSERT INTO `base_info` VALUES (2, 2, '李四', '女', '1990-06-06', '无');
 23INSERT INTO `base_info` VALUES (3, 3, '王五', '男', '1988-01-27', '无');
 24INSERT INTO `base_info` VALUES (4, 4, '赵六', '女', '1991-05-06', '无');
 25INSERT INTO `base_info` VALUES (5, 5, '孙七', '男', '1995-03-21', '无');
 26INSERT INTO `base_info` VALUES (6, 6, '周八', '女', '1989-11-22', '无');
 27
 28-- ----------------------------
 29-- Table structure for group
 30-- ----------------------------
 31DROP TABLE IF EXISTS `group`;
 32CREATE TABLE `group`  (
 33  `id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
 34  `name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '组名',
 35  PRIMARY KEY (`id`) USING BTREE
 36) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;
 37
 38-- ----------------------------
 39-- Records of group
 40-- ----------------------------
 41INSERT INTO `group` VALUES (1, '测试组1');
 42INSERT INTO `group` VALUES (2, '测试组2');
 43
 44-- ----------------------------
 45-- Table structure for role
 46-- ----------------------------
 47DROP TABLE IF EXISTS `role`;
 48CREATE TABLE `role`  (
 49  `id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
 50  `name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '角色名称',
 51  PRIMARY KEY (`id`) USING BTREE
 52) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;
 53
 54-- ----------------------------
 55-- Records of role
 56-- ----------------------------
 57INSERT INTO `role` VALUES (1, '管理员');
 58INSERT INTO `role` VALUES (2, '测试');
 59INSERT INTO `role` VALUES (3, '开发');
 60INSERT INTO `role` VALUES (4, '运维');
 61INSERT INTO `role` VALUES (5, '产品');
 62INSERT INTO `role` VALUES (6, '需求');
 63
 64-- ----------------------------
 65-- Table structure for user
 66-- ----------------------------
 67DROP TABLE IF EXISTS `user`;
 68CREATE TABLE `user`  (
 69  `id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键',
 70  `group_id` int(0) NULL DEFAULT NULL COMMENT '组号',
 71  `username` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '用户名',
 72  `password` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '密码',
 73  PRIMARY KEY (`id`) USING BTREE
 74) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;
 75
 76-- ----------------------------
 77-- Records of user
 78-- ----------------------------
 79INSERT INTO `user` VALUES (1, 1, 'zhangsan', '123456');
 80INSERT INTO `user` VALUES (2, 1, 'lisi', '123456');
 81INSERT INTO `user` VALUES (3, 1, 'wangwu', '123456');
 82INSERT INTO `user` VALUES (4, 2, 'zhaoliu', '123456');
 83INSERT INTO `user` VALUES (5, 2, 'sunqi', '123456');
 84INSERT INTO `user` VALUES (6, 2, 'zhouba', '123456');
 85
 86-- ----------------------------
 87-- Table structure for user_role
 88-- ----------------------------
 89DROP TABLE IF EXISTS `user_role`;
 90CREATE TABLE `user_role`  (
 91  `id` int(0) NOT NULL COMMENT '主键',
 92  `user_id` int(0) NULL DEFAULT NULL COMMENT '用户ID',
 93  `role_id` int(0) NULL DEFAULT NULL COMMENT '角色ID',
 94  PRIMARY KEY (`id`) USING BTREE
 95) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;
 96
 97-- ----------------------------
 98-- Records of user_role
 99-- ----------------------------
100INSERT INTO `user_role` VALUES (1, 1, 1);
101INSERT INTO `user_role` VALUES (2, 1, 2);
102INSERT INTO `user_role` VALUES (3, 1, 3);
103INSERT INTO `user_role` VALUES (4, 2, 2);
104INSERT INTO `user_role` VALUES (5, 2, 3);
105INSERT INTO `user_role` VALUES (6, 3, 4);
106INSERT INTO `user_role` VALUES (7, 4, 4);
107INSERT INTO `user_role` VALUES (8, 5, 5);
108INSERT INTO `user_role` VALUES (9, 5, 6);
109INSERT INTO `user_role` VALUES (10, 6, 5);
110
111SET FOREIGN_KEY_CHECKS = 1;

三、示例项目基础配置

3.1 引入 Maven 相关依赖

这里是使用 Maven 进行相关依赖管理,引入的依赖如下:

 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    <parent>
 7        <groupId>org.springframework.boot</groupId>
 8        <artifactId>spring-boot-starter-parent</artifactId>
 9        <version>2.2.5.RELEASE</version>
10    </parent>
11
12    <groupId>club.mydlq</groupId>
13    <artifactId>springboot-mybatis-example</artifactId>
14    <version>1.0.0</version>
15    <name>springboot-mybatis-example</name>
16    <description>springboot mybatis example project</description>
17
18    <properties>
19        <java.version>1.8</java.version>
20    </properties>
21
22    <dependencies>
23        <!--web-->
24        <dependency>
25            <groupId>org.springframework.boot</groupId>
26            <artifactId>spring-boot-starter-web</artifactId>
27        </dependency>
28        <!--lombok -->
29        <dependency>
30            <groupId>org.projectlombok</groupId>
31            <artifactId>lombok</artifactId>
32            <optional>true</optional>
33        </dependency>
34        <!--mysql-->
35        <dependency>
36            <groupId>mysql</groupId>
37            <artifactId>mysql-connector-java</artifactId>
38        </dependency>
39        <!--mybatis-->
40        <dependency>
41            <groupId>org.mybatis.spring.boot</groupId>
42            <artifactId>mybatis-spring-boot-starter</artifactId>
43            <version>2.1.2</version>
44        </dependency>
45        <!--swagger-->
46        <dependency>
47            <groupId>io.springfox</groupId>
48            <artifactId>springfox-swagger2</artifactId>
49            <version>2.9.2</version>
50        </dependency>
51        <dependency>
52            <groupId>io.springfox</groupId>
53            <artifactId>springfox-swagger-ui</artifactId>
54            <version>2.9.2</version>
55        </dependency>
56    </dependencies>
57
58    <build>
59        <plugins>
60            <plugin>
61                <groupId>org.springframework.boot</groupId>
62                <artifactId>spring-boot-maven-plugin</artifactId>
63            </plugin>
64        </plugins>
65    </build>
66
67</project>

依赖说明:

  • spring-boot-starter-parent: SpringBoot 父依赖。
  • spring-boot-starter-web: SpringBoot web 依赖。
  • lombok: 项目集成组件,用于使用注解方式快速构建实体类对象的 Get、Set 和其他一些便捷方法。
  • mysql-connector-java: 用于连接 Mysql 的驱动。
  • mybatis-spring-boot-starter: SpringBoot 与 Mybatis 集成的依赖。
  • springfox-swagger2: Swagger 组件,用于暴露项目的 API 信息,方便进行测试工作。
  • springfox-swagger-ui: Swagger 组件,用于对 Swagger 暴露的项目 API 生成对应 WEB UI 页面。

3.2 配置相关参数

进入 application.yml 文件,配置数据库相关参数,内容如下:

 1spring:
 2  application:
 3    name: springboot-mybatis-example
 4  datasource:
 5    type: com.zaxxer.hikari.HikariDataSource
 6    driverClassName: com.mysql.cj.jdbc.Driver
 7    url: jdbc:mysql://127.0.0.1:3306/mybatis_example?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true
 8    hikari:
 9      pool-name: DatebookHikariCP
10      minimum-idle: 5
11      maximum-pool-size: 15
12      max-lifetime: 1800000
13      connection-timeout: 30000
14      username: root
15      password: 123456
16
17mybatis:
18  mapper-locations: classpath:mappers/*.xml

参数说明:

  • spring.datasource.type: 指定使用的数据库连接池。
  • spring.datasource.driverClassName: 指定使用的数据库驱动。
  • spring.datasource.url: 数据库地址。
  • spring.datasource.username: 数据库用户名。
  • spring.datasource.password: 数据库密码。
  • spring.datasource.hikari.pool-name: 指定使用的数据库连接池。
  • spring.datasource.hikari.minimum-idle: 连接池最小最小空闲连接。
  • spring.datasource.hikari.maximum-pool-size: 连接池最大连接数。
  • spring.datasource.hikari.max-lifetime: 连接池连接最大存活时间。
  • spring.datasource.hikari.connection-timeout: 连接池连接超时时间。
  • mybatis.mapper-locations: 指定 Mybatis Mapper xml 文件的位置。

3.3 单表实体类对象

数据库中每个表都有多个字段,需要提前在项目中创建与各个表字段关联的实体类,以方便后续数据库信息转换为 Java 对象,实体类如下:

Group.java

1import lombok.Data;
2
3@Data
4public class Group {
5    /** 主键ID */
6    private Integer id;
7    /** 组名 */
8    private String name;
9}

User.java

 1import lombok.Data;
 2
 3@Data
 4public class User {
 5    /** 主键ID */
 6    private Integer id;
 7    /** 组号 */
 8    private Integer groupId;
 9    /** 用户名 */
10    private String username;
11    /** 密码 */
12    private String password;
13}

Role.java

1import lombok.Data;
2
3@Data
4public class Role {
5    /** 主键ID */
6    private Integer id;
7    /** 角色名称 */
8    private String name;
9}

BaseInfo.java

 1import lombok.Data;
 2import java.util.Date;
 3
 4@Data
 5public class BaseInfo {
 6    /** 主键ID */
 7    private Integer id;
 8    /** 用户ID */
 9    private String userId;
10    /** 姓名 */
11    private String name;
12    /** 性别 */
13    private String sex;
14    /** 出生日期 */
15    private Date birthday;
16    /** 备注 */
17    private String remark;
18}

3.4 多表实体类对象

多表实体类对象指的是,将之前的单表实体聚合,然后一个实体对象参数中包含另一个实体对象的集合,方便后续多表查询演示,实体对象内容如下:

UserInfo.java

 1import club.mydlq.model.single.BaseInfo;
 2import club.mydlq.model.single.User;
 3import lombok.Data;
 4import lombok.EqualsAndHashCode;
 5
 6@Data
 7@EqualsAndHashCode(callSuper = true)
 8public class UserInfo extends User {
 9
10    /** 用户基本信息 */
11    private BaseInfo baseInfo;
12    
13}

GroupUser.java

 1import club.mydlq.model.single.Group;
 2import club.mydlq.model.single.User;
 3import lombok.Data;
 4import lombok.EqualsAndHashCode;
 5import java.util.List;
 6
 7@Data
 8@EqualsAndHashCode(callSuper = true)
 9public class GroupUser extends Group {
10
11    /** 用户列表 */
12    private List<User> users;
13    
14}

GroupUserRole.java

 1import club.mydlq.model.single.Group;
 2import lombok.Data;
 3import lombok.EqualsAndHashCode;
 4import java.util.List;
 5
 6@Data
 7@EqualsAndHashCode(callSuper = true)
 8public class GroupUserRole extends Group {
 9
10    /** 用户角色列表 */
11    private List<UserRole> users;
12
13}

UserRole.java

 1import club.mydlq.model.single.Role;
 2import club.mydlq.model.single.User;
 3import lombok.Data;
 4import lombok.EqualsAndHashCode;
 5import java.util.List;
 6
 7@Data
 8@EqualsAndHashCode(callSuper = true)
 9public class UserRole extends User {
10
11    /** 角色列表 */
12    private List<Role> roles;
13
14}

3.5 项目启动类

SpringBoot 项目的启动类。

 1import org.springframework.boot.SpringApplication;
 2import org.springframework.boot.autoconfigure.SpringBootApplication;
 3
 4@SpringBootApplication
 5public class Application {
 6
 7    public static void main(String[] args) {
 8        SpringApplication.run(Application.class, args);
 9    }
10
11}

四、示例项目 Mapper

Mybatis 的规则,在执行 Sql 语句进行数据库操作时,需要提前创建接口类来定义数据库操作方法,便于项目中其它类调用。然后还需要创建 xml 文件跟对应 Mapper 接口类绑定,实现接口中的方法,在里面按 Mybatis 规则写 SQL 语句。

4.1 单表 CURD 操作

"用户表"操作接口类:

 1import java.util.List;
 2import club.mydlq.model.single.User;
 3import org.apache.ibatis.annotations.Mapper;
 4import org.apache.ibatis.annotations.Param;
 5
 6@Mapper
 7public interface UserMapper {
 8
 9    /**
10     * 查询全部用户数据列表
11     *
12     * @return 用户信息列表
13     */
14    List<User> selectAll();
15
16    /**
17     * 根据主键ID查询用户
18     *
19     * @param id 主键ID
20     * @return 用户
21     */
22    User selectById(@Param("id") Integer id);
23
24    /**
25     * 根据用户名模糊查询用户
26     *
27     * @param username 用户名
28     * @return 用户
29     */
30    User selectByUsername(@Param("username") String username);
31
32    /**
33     * 根据主键ID更新用户
34     *
35     * @param user 用户实体对象
36     * @return 是否更新成功
37     */
38    Boolean updateById(@Param("user") User user);
39
40    /**
41     * 插入用户
42     *
43     * @param user 用户实体对象
44     * @return 是否插入成功
45     */
46    Boolean insert(@Param("user") User user);
47
48    /**
49     * 插入用户并返回主键ID到实体对象
50     *
51     * @param user 用户实体对象
52     * @return 是否插入成功
53     */
54    Boolean insertAndReturnId(@Param("user") User user);
55
56    /**
57     * 根据主键ID删除用户信息
58     *
59     * @param id 主键
60     * @return 是否删除成功
61     */
62    Boolean deleteById(@Param("id") Integer id);
63
64}

"用户表"操作 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
 4<!--User 表操作,单表操作示例-->
 5<mapper namespace="club.mydlq.mappers.single.UserMapper">
 6
 7    <!--结果映射参数设置-->
 8    <resultMap id="UserResultMap" type="club.mydlq.model.single.User">
 9        <id column="id" jdbcType="INTEGER" property="id"/>
10        <result column="group_id" jdbcType="INTEGER" property="groupId"/>
11        <result column="password" jdbcType="VARCHAR" property="password"/>
12        <result column="username" jdbcType="VARCHAR" property="username"/>
13    </resultMap>
14
15    <!-- 查询全部用户列表 -->
16    <select id="selectAll" resultMap="UserResultMap">
17        SELECT id, group_id, username, password
18        FROM `user`
19    </select>
20
21    <!--根据主键ID查询用户-->
22    <select id="selectById" parameterType="java.lang.Integer" resultMap="UserResultMap">
23        SELECT id, group_id, username, password
24        FROM `user`
25        WHERE id = #{id, jdbcType=INTEGER}
26    </select>
27
28    <!--根据用户名模糊查询用户-->
29    <select id="selectByUsername" parameterType="java.lang.String" resultMap="UserResultMap">
30        SELECT id, group_id, username, password
31        FROM `user`
32        WHERE username LIKE concat('%', #{username, jdbcType=INTEGER}, '%')
33    </select>
34
35    <!-- 插入用户 -->
36    <insert id="insert" parameterType="club.mydlq.model.single.User">
37        INSERT INTO `user`
38        <trim prefix="(" suffix=")" suffixOverrides=",">
39            <if test="groupId != null">group_id,</if>
40            <if test="username != null">username,</if>
41            <if test="password != null">password,</if>
42        </trim>
43        <trim prefix="values(" suffix=")" suffixOverrides=",">
44            <if test="groupId != null">#{groupId, jdbcType=INTEGER},</if>
45            <if test="username != null">#{username, jdbcType=VARCHAR},</if>
46            <if test="password != null">#{password, jdbcType=VARCHAR},</if>
47        </trim>
48    </insert>
49
50    <!-- 插入用户并返回主键ID -->
51    <insert id="insertAndReturnId" parameterType="club.mydlq.model.single.User"
52            useGeneratedKeys="true" keyProperty="id" keyColumn="id">
53        INSERT INTO `user`
54        <trim prefix="(" suffix=")" suffixOverrides=",">
55            <if test="groupId != null">group_id,</if>
56            <if test="username != null">username,</if>
57            <if test="password != null">password,</if>
58        </trim>
59        <trim prefix="values(" suffix=")" suffixOverrides=",">
60            <if test="groupId != null">#{groupId, jdbcType=INTEGER},</if>
61            <if test="username != null">#{username, jdbcType=VARCHAR},</if>
62            <if test="password != null">#{password, jdbcType=VARCHAR},</if>
63        </trim>
64    </insert>
65
66    <!--更新用户-->
67    <update id="updateById" parameterType="club.mydlq.model.single.User">
68        UPDATE `user`
69        <set>
70            <if test="groupId != null">group_id = #{groupId, jdbcType=INTEGER},</if>
71            <if test="username != null">username = #{username, jdbcType=VARCHAR},</if>
72            <if test="password != null">password = #{password, jdbcType=VARCHAR},</if>
73        </set>
74        WHERE id = #{id, jdbcType=INTEGER}
75    </update>
76
77    <!-- 删除用户信息 -->
78    <delete id="deleteById" parameterType="java.lang.Integer">
79        DELETE
80        FROM `user`
81        WHERE id = #{id, jdbcType=INTEGER}
82    </delete>
83
84</mapper>

4.2 单表 CURD 批量操作

"用户表"批量操作接口类:

 1import club.mydlq.model.single.User;
 2import org.apache.ibatis.annotations.Mapper;
 3import org.apache.ibatis.annotations.Param;
 4import java.util.List;
 5
 6/**
 7 * User 表批量操作 Mapper
 8 */
 9@Mapper
10public interface UserBatchMapper {
11
12    /**
13     * 批量查询用户
14     *
15     * @param ids 用户ID列表
16     * @return 用户列表
17     */
18    List<User> selectBatch(@Param("ids") List<Integer> ids);
19
20    /**
21     * 批量插入用户
22     *
23     * @param userList 用户列表
24     * @return 是否插入成功
25     */
26    Boolean insertBatch(@Param("userList") List<User> userList);
27
28    /**
29     * 批量更新用户
30     *
31     * @param userList 用户列表
32     * @return 是否更新成功
33     */
34    Boolean updateBatch(@Param("userList") List<User> userList);
35
36    /**
37     * 批量查询用户
38     *
39     * @param ids 用户ID列表
40     * @return 用户列表
41     */
42    Boolean deleteBatch(@Param("ids") List<Integer> ids);
43
44}

"用户表"批量操作 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
 4<!--User 表操作,单表操作示例-->
 5<mapper namespace="club.mydlq.mappers.single.UserBatchMapper">
 6
 7    <!--结果映射参数设置-->
 8    <resultMap id="UserResultMap" type="club.mydlq.model.single.User">
 9        <id column="id" jdbcType="INTEGER" property="id"/>
10        <result column="group_id" jdbcType="INTEGER" property="groupId"/>
11        <result column="password" jdbcType="VARCHAR" property="password"/>
12        <result column="username" jdbcType="VARCHAR" property="username"/>
13    </resultMap>
14
15    <!--批量查询-->
16    <select id="selectBatch" parameterType="java.util.List" resultMap="UserResultMap">
17        SELECT id, group_id, username, password
18        FROM `user`
19        WHERE id IN
20        <trim prefix="(" suffix=")">
21            <foreach collection="ids" index="index" item="id" separator=",">
22                #{id}
23            </foreach>
24        </trim>
25    </select>
26
27    <!-- 批量插入用户 -->
28    <insert id="insertBatch" parameterType="java.util.List">
29        INSERT INTO `user` (`group_id`, `username`, `password`)
30        VALUES
31        <foreach collection="userList" item="user" index="index" separator=",">
32            (
33            #{user.groupId, jdbcType=INTEGER},
34            #{user.username, jdbcType=VARCHAR},
35            #{user.password, jdbcType=VARCHAR}
36            )
37        </foreach>
38    </insert>
39
40    <!-- 批量更新用户 -->
41    <update id="updateBatch" parameterType="java.util.List">
42        <foreach collection="userList" item="user" index="index" separator=";">
43            UPDATE `user`
44            <set>
45                <if test="user.groupId != null">group_id=#{user.groupId, jdbcType=INTEGER},</if>
46                <if test="user.username != null">username=#{user.username, jdbcType=VARCHAR},</if>
47                <if test="user.password != null">password=#{user.password, jdbcType=VARCHAR},</if>
48            </set>
49            WHERE id = #{user.id, jdbcType=INTEGER}
50        </foreach>
51    </update>
52
53    <!-- 批量删除用户信息 -->
54    <delete id="deleteBatch" parameterType="java.util.List">
55        DELETE
56        FROM `user`
57        WHERE id IN
58        <trim prefix="(" suffix=")">
59            <foreach collection="ids" index="index" item="id" separator=",">
60                #{id}
61            </foreach>
62        </trim>
63    </delete>
64
65</mapper>

4.3 多表一对一操作

"用户表"与"用户基本信息表"操作接口类:

 1import club.mydlq.model.many.UserInfo;
 2import org.apache.ibatis.annotations.Mapper;
 3import org.apache.ibatis.annotations.Param;
 4import java.util.List;
 5
 6@Mapper
 7public interface UserInfoMapper {
 8
 9    /**
10     * 根据用户ID查询用户与用户基本信息
11     *
12     * @param userId 用户ID
13     * @return 用户与用户基本信息
14     */
15    UserInfo selectByUserId(@Param("userId") Integer userId);
16
17    /**
18     * 查询全部用户与用户基本信息
19     *
20     * @return 用户与基本信息列表
21     */
22    List<UserInfo> selectAll();
23
24}

"用户表"与"用户基本信息表"操作 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
 4<mapper namespace="club.mydlq.mappers.many.UserInfoMapper">
 5
 6    <!--结果映射参数设置-->
 7    <resultMap id="UserInfoResultMap" type="club.mydlq.model.many.UserInfo">
 8        <id column="id" jdbcType="INTEGER" property="id"/>
 9        <result column="group_id" jdbcType="INTEGER" property="groupId"/>
10        <result column="username" jdbcType="VARCHAR" property="username"/>
11        <result column="password" jdbcType="VARCHAR" property="password"/>
12        <association property="baseInfo" javaType="club.mydlq.model.single.BaseInfo">
13            <id column="baseId" jdbcType="INTEGER" property="id"/>
14            <result column="userId" jdbcType="INTEGER" property="userId"/>
15            <result column="name" jdbcType="VARCHAR" property="name"/>
16            <result column="sex" jdbcType="VARCHAR" property="sex"/>
17            <result column="birthday" jdbcType="DATE" property="birthday"/>
18            <result column="remark" jdbcType="VARCHAR" property="remark"/>
19        </association>
20    </resultMap>
21
22    <!-- 查询全部用户信息列表 -->
23    <select id="selectAll" resultMap="UserInfoResultMap">
24        SELECT A.id, A.group_id, A.username, A.password,
25               B.id AS baseId, B.user_id AS userId, B.name, B.sex, B.birthday, B.remark
26        FROM `user` AS A,
27             `base_info` AS B
28    </select>
29
30    <!--查询用户信息-->
31    <select id="selectByUserId" parameterType="java.lang.Integer" resultMap="UserInfoResultMap">
32        SELECT A.id, A.group_id, A.username, A.password,
33               B.id AS baseId, B.user_id AS userId, B.name, B.sex, B.birthday, B.remark
34        FROM `user` AS A,
35             `base_info` AS B
36        WHERE A.id = B.user_id AND
37              A.id = #{userId, jdbcType=INTEGER}
38    </select>
39
40</mapper>

4.4 多表一对多操作

"用户组表"与"用户表"操作接口类:

 1import club.mydlq.model.many.GroupUser;
 2import org.apache.ibatis.annotations.Mapper;
 3import org.apache.ibatis.annotations.Param;
 4
 5@Mapper
 6public interface GroupUserMapper {
 7
 8    /**
 9     * 根据组ID查询用户列表
10     *
11     * @param groupId 组ID
12     * @return 用户列表
13     */
14    GroupUser selectByGroupId(@Param("groupId") Integer groupId);
15
16}

"用户组表"与"用户表"操作 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
 4<mapper namespace="club.mydlq.mappers.many.GroupUserMapper">
 5
 6    <!--结果映射参数设置-->
 7    <resultMap id="GroupUserResultMap" type="club.mydlq.model.many.GroupUser">
 8        <id column="id" jdbcType="INTEGER" property="id"/>
 9        <result column="name" jdbcType="VARCHAR" property="name"/>
10        <collection property="users" ofType="club.mydlq.model.single.User">
11            <id column="userId" jdbcType="INTEGER" property="id"/>
12            <result column="group_id" jdbcType="INTEGER" property="groupId"/>
13            <result column="username" jdbcType="VARCHAR" property="username"/>
14            <result column="password" jdbcType="VARCHAR" property="password"/>
15        </collection>
16    </resultMap>
17
18    <!-- 查询某个组与组内用户列表 -->
19    <select id="selectByGroupId" parameterType="java.lang.Integer" resultMap="GroupUserResultMap">
20        SELECT A.id,A.name,
21               B.id AS userId, B.group_id, B.username, B.password
22        FROM `group` AS A,
23             `user` AS B
24        WHERE A.id = B.group_id AND
25              A.id = #{groupId, jdbcType=INTEGER}
26    </select>
27
28</mapper>

4.5 多表一对多对多操作

"用户组表"、"用户表"、"角色表"与"用户角色表"操作接口类:

 1import club.mydlq.model.many.GroupUserRole;
 2import org.apache.ibatis.annotations.Mapper;
 3import org.apache.ibatis.annotations.Param;
 4import java.util.List;
 5
 6@Mapper
 7public interface GroupUserRoleMapper {
 8
 9    /**
10     * 根据组ID查找某个用户组下的全部用户与用户关联角色信息
11     *
12     * @param groupId 组ID
13     * @return 用户与用户角色信息列表
14     */
15    List<GroupUserRole> selectUserAndRoleByGroupId(@Param("groupId") Integer groupId);
16
17}

"用户组表"、"用户表"、"角色表"与"用户角色表"操作 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
 4<mapper namespace="club.mydlq.mappers.many.GroupUserRoleMapper">
 5    
 6    <!--结果映射参数设置-->
 7    <resultMap id="GroupUserRoleResultMap" type="club.mydlq.model.many.GroupUserRole">
 8        <id column="id" jdbcType="INTEGER" property="id"/>
 9        <result column="name" jdbcType="VARCHAR" property="name"/>
10        <collection property="users" ofType="club.mydlq.model.many.UserRole">
11            <id column="userId" jdbcType="INTEGER" property="id"/>
12            <result column="group_id" jdbcType="INTEGER" property="groupId"/>
13            <result column="username" jdbcType="VARCHAR" property="username"/>
14            <result column="password" jdbcType="VARCHAR" property="password"/>
15            <collection property="roles" ofType="club.mydlq.model.single.Role">
16                <id column="roleId" jdbcType="INTEGER" property="id"/>
17                <result column="roleName" jdbcType="VARCHAR" property="name"/>
18            </collection>
19        </collection>
20    </resultMap>
21
22    <!--根据用户组ID查询用户和用户关联的全部角色-->
23    <select id="selectUserAndRoleByGroupId" parameterType="java.lang.Integer" resultMap="GroupUserRoleResultMap">
24        select A.id, A.name,
25               B.id AS userId, B.group_id, B.username, B.password,
26               C.id AS roleId, C.name AS roleName
27        FROM `group` AS A,
28             `user` AS B,
29             `role` AS C,
30             `user_role` AS D
31        WHERE A.id = B.group_id AND
32              B.id = D.user_id AND
33              C.id = D.role_id AND
34              A.id = #{groupId, jdbcType=INTEGER}
35    </select>
36
37</mapper>

五、示例项目测试 Controller

5.1 创建 Swagger 配置类

 1import com.google.common.base.Predicates;
 2import org.springframework.context.annotation.Bean;
 3import org.springframework.context.annotation.Configuration;
 4import springfox.documentation.builders.ApiInfoBuilder;
 5import springfox.documentation.builders.PathSelectors;
 6import springfox.documentation.builders.RequestHandlerSelectors;
 7import springfox.documentation.service.ApiInfo;
 8import springfox.documentation.spi.DocumentationType;
 9import springfox.documentation.spring.web.plugins.Docket;
10import springfox.documentation.swagger2.annotations.EnableSwagger2;
11
12@Configuration
13@EnableSwagger2
14public class SwaggerConfig {
15
16    @Bean
17    public Docket createRestApi() {
18        return new Docket(DocumentationType.SWAGGER_2)
19                .apiInfo(apiInfo())
20                .select()
21                .apis(RequestHandlerSelectors.any())
22                .paths(PathSelectors.any())
23                .paths(Predicates.not(PathSelectors.regex("/error.*")))
24                .paths(Predicates.not(PathSelectors.regex("/actuator.*")))
25                .build();
26    }
27
28    private ApiInfo apiInfo() {
29        return new ApiInfoBuilder()
30                .title("springboot 集成 mybatis")
31                .description("springboot 集成 mybatis 示例接口")
32                .version("1.0.0")
33                .build();
34    }
35
36}

5.2 创建用于测试的 Controller 类

UserController.java(用户接口,单表操作)

 1import club.mydlq.mappers.single.UserMapper;
 2import club.mydlq.model.single.User;
 3import io.swagger.annotations.Api;
 4import io.swagger.annotations.ApiOperation;
 5import org.springframework.web.bind.annotation.*;
 6import javax.annotation.Resource;
 7
 8@RestController
 9@RequestMapping("/user")
10@Api(tags = "用户接口(单表操作)")
11public class UserController {
12
13    @Resource
14    private UserMapper userMapper;
15
16    @GetMapping("/all")
17    @ApiOperation(value = "查询全部\"用户\"", notes = "测试查询全部\"用户\"。")
18    public Object getUserAll() {
19        return userMapper.selectAll();
20    }
21
22    @GetMapping("/{id}")
23    @ApiOperation(value = "查询\"用户\"", notes = "测试查询\"用户\"。")
24    public Object getUser(@PathVariable Integer id) {
25        return userMapper.selectById(id);
26    }
27
28    @GetMapping("/username/{username}")
29    @ApiOperation(value = "根据\"用户名\"查询\"用户\"", notes = "测试根据\"用户名\"查询\"用户\"。")
30    public Object getUserByUsername(@PathVariable String username){
31        return userMapper.selectByUsername(username);
32    }
33
34    @PostMapping
35    @ApiOperation(value = "插入\"用户\"", notes = "测试插入\"用户\"。")
36    public Object saveUser(@RequestBody User user) {
37        return userMapper.insert(user);
38    }
39
40    @PostMapping("/return")
41    @ApiOperation(value = "插入\"用户\"并且返回\"主键ID\"", notes = "测试插入\"用户\"并且返回\"主键ID\"。")
42    public Object saveUserAndReturnId(@RequestBody User user) {
43        boolean inserted = userMapper.insertAndReturnId(user);
44        if (inserted){
45            return user.getId();
46        }
47        return "插入失败";
48    }
49
50    @PutMapping
51    @ApiOperation(value = "更新\"用户\"", notes = "测试更新\"用户\"。")
52    public Object updateUser(@RequestBody User user) {
53        return userMapper.updateById(user);
54    }
55
56    @DeleteMapping("/{id}")
57    @ApiOperation(value = "删除\"用户\"", notes = "测试删除\"用户\"。")
58    public Object deleteUser(@PathVariable Integer id) {
59        return userMapper.deleteById(id);
60    }
61
62}

UserBatchController.java(用户接口,单表批量操作)

 1import club.mydlq.mappers.single.UserBatchMapper;
 2import club.mydlq.model.single.User;
 3import io.swagger.annotations.Api;
 4import io.swagger.annotations.ApiOperation;
 5import org.springframework.web.bind.annotation.*;
 6import javax.annotation.Resource;
 7import java.util.List;
 8
 9@RestController
10@RequestMapping("/userBatch")
11@Api(tags = "用户接口(单表批量操作)")
12public class UserBatchController {
13
14    @Resource
15    private UserBatchMapper userBatchMapper;
16
17    @PostMapping("/find")
18    @ApiOperation(value = "批量查询\"用户\"", notes = "测试批量查询\"用户\"。")
19    public Object getUserBatch(@RequestBody List<Integer> ids) {
20        return userBatchMapper.selectBatch(ids);
21    }
22
23    @PostMapping("/save")
24    @ApiOperation(value = "批量插入\"用户\"", notes = "测试批量插入\"用户\"")
25    public Object saveUserBatch(@RequestBody List<User> userList) {
26        return userBatchMapper.insertBatch(userList);
27    }
28
29    @PutMapping("/update")
30    @ApiOperation(value = "批量更新\"用户\"", notes = "测试批量更新\"用户\"")
31    public Object updateUserBatch(@RequestBody List<User> userList) {
32        return userBatchMapper.updateBatch(userList);
33    }
34
35    @DeleteMapping("/delete")
36    @ApiOperation(value = "批量删除\"用户\"", notes = "测试批量删除\"用户\"")
37    public Object deleteUserBatch(@RequestBody List<Integer> ids) {
38        return userBatchMapper.deleteBatch(ids);
39    }
40
41}

UserInfoController.java(用户与用户信息接口,多表查询,一对一)

 1import club.mydlq.mappers.many.UserInfoMapper;
 2import io.swagger.annotations.Api;
 3import io.swagger.annotations.ApiOperation;
 4import org.springframework.web.bind.annotation.GetMapping;
 5import org.springframework.web.bind.annotation.PathVariable;
 6import org.springframework.web.bind.annotation.RequestMapping;
 7import org.springframework.web.bind.annotation.RestController;
 8import javax.annotation.Resource;
 9
10@RestController
11@RequestMapping("/userInfo")
12@Api(tags = "用户与用户信息接口(多表查询,一对一)")
13public class UserInfoController {
14
15    @Resource
16    private UserInfoMapper userInfoMapper;
17
18    @GetMapping("/all")
19    @ApiOperation(value = "查询全部\"用户与用户信息\"列表", notes = "测试查询全部\"用户与用户信息\"列表。")
20    public Object getUserInfoAll() {
21        return userInfoMapper.selectAll();
22    }
23
24    @GetMapping("/{userId}")
25    @ApiOperation(value = "查询某个\"用户与用户信息\"", notes = "测试查询某个\"用户与用户信息。")
26    public Object getUserInfo(@PathVariable Integer userId) {
27        return userInfoMapper.selectByUserId(userId);
28    }
29
30}

GroupUserController.java(组与用户接口(多表操作,一对多))

 1import club.mydlq.mappers.many.GroupUserMapper;
 2import io.swagger.annotations.Api;
 3import io.swagger.annotations.ApiOperation;
 4import org.springframework.web.bind.annotation.GetMapping;
 5import org.springframework.web.bind.annotation.PathVariable;
 6import org.springframework.web.bind.annotation.RequestMapping;
 7import org.springframework.web.bind.annotation.RestController;
 8import javax.annotation.Resource;
 9
10@RestController
11@RequestMapping("/groupUser")
12@Api(tags = "组与用户接口(多表操作,一对多)")
13public class GroupUserController {
14
15    @Resource
16    private GroupUserMapper groupUserMapper;
17
18    @GetMapping("/{userId}")
19    @ApiOperation(value = "查询某组\"用户\"列表", notes = "测试查询某组\"用户\"列表。")
20    public Object getUserInfo(@PathVariable Integer userId) {
21        return groupUserMapper.selectByGroupId(userId);
22    }
23
24}

GroupUserRoleController.java(组、用户与角色接口,多表查询,一对一对多)

 1import club.mydlq.mappers.many.GroupUserRoleMapper;
 2import io.swagger.annotations.Api;
 3import io.swagger.annotations.ApiOperation;
 4import org.springframework.web.bind.annotation.GetMapping;
 5import org.springframework.web.bind.annotation.PathVariable;
 6import org.springframework.web.bind.annotation.RequestMapping;
 7import org.springframework.web.bind.annotation.RestController;
 8import javax.annotation.Resource;
 9
10@RestController
11@RequestMapping("/GroupUserRole")
12@Api(tags = "组、用户与角色接口(多表查询,一对一对多)")
13public class GroupUserRoleController {
14
15    @Resource
16    private GroupUserRoleMapper groupUserRoleMapper;
17
18    @GetMapping("/{groupId}")
19    @ApiOperation(value = "查询某组\"用户与角色\"列表", notes = "测试查询某组\"用户与角色\"列表。")
20    public Object getUserInfo(@PathVariable Integer groupId) {
21        return groupUserRoleMapper.selectUserAndRoleByGroupId(groupId);
22    }
23
24}

六、 启动项目进行测试

访问 Swagger 页面,对各个接口进行测试:

---END---


  !版权声明:本博客内容均为原创,每篇博文作为知识积累,写博不易,转载请注明出处。