在之前的 Spring学习之旅(十二)--持久化框架 中我们介绍了 JPA
的使用,今天我们就来了解下另一种持久化框架 Mybatis。
一、集成 Mybatis
1.1 准备工作
新建用户表
CREATE TABLE `sys_user` (
`user_id` bigint(21) NOT NULL COMMENT '用户编码',
`user_name` varchar(50) DEFAULT NULL COMMENT '用户名',
`age` int(3) DEFAULT NULL COMMENT '年龄',
`email` varchar(100) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
添加依赖
<dependencies>
......
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
</dependencies>
新建实体类:
@Data
public class SysUser {
private Long userId;
private String userName;
private int age;
private String email;
}
1.2注解形式
@Mapper
public interface SysUserAnnotationMapper {
@Insert("INSERT INTO sys_user VALUES(#{userId},#{userName},#{age},#{email})")
int add(SysUser sysUser);
@Select("SELECT * FROM sys_user")
@Results({
@Result(property = "userId", column = "user_id", javaType = Long.class),
@Result(property = "userName", column = "user_name"),
@Result(property = "age", column = "age"),
@Result(property = "email", column = "email")
})
List<SysUser> getAll();
}
新建测试类:
@SpringBootTest
public class AnnotationMapperTest {
@Autowired
private SysUserAnnotationMapper userMapper;
// JUnit5 开始 @Before 和@After被 @BeforeEach 和 @AfterEach给替代
@BeforeEach
public void setUp() {
testDelete();
}
@Test
public void test() {
testAdd();
testGetList();
}
private void testDelete() {
userMapper.delete();
List<SysUser> result = userMapper.getAll();
Assert.assertTrue(result.size() == 0);
}
private void testAdd() {
SysUser user = getOneUser();
int result = userMapper.add(user);
Assert.assertEquals(1, result);
}
private void testGetList() {
SysUser user = getOneUser();
List<SysUser> userList = userMapper.getAll();
Assert.assertTrue(userList.size() > 0);
Assert.assertEquals(user, userList.get(0));
}
private SysUser getOneUser() {
SysUser user = new SysUser();
user.setUserId(new Long("1572228567336"));
user.setUserName("MarkLogZhu");
user.setAge(26);
user.setEmail("marklogzhu@163.com");
return user;
}
}
1.3 传统 XML 形式
在 application.yml
文件中指定 XML 和配置文件文件位置
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis//mapper/*.xml
在 resources/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>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer"/>
<typeAlias alias="Long" type="java.lang.Long"/>
<typeAlias alias="HashMap" type="java.util.HashMap"/>
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap"/>
<typeAlias alias="ArrayList" type="java.util.ArrayList"/>
<typeAlias alias="LinkedList" type="java.util.LinkedList"/>
</typeAliases>
</configuration>
在 resources/mybatis/mapper
目录下新建 SysUserXmlMapper.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.learm.springboot.dao.SysUserXmlMapper">
<resultMap id="BaseResultMap" type="com.learm.springboot.domain.entity.SysUser">
<id column="user_id" property="userId" jdbcType="BIGINT"/>
<result column="user_name" property="userName" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="INTEGER"/>
<result column="email" property="email" jdbcType="VARCHAR"/>
</resultMap>
<select id="getAll" resultMap="BaseResultMap">
SELECT * FROM sys_user
</select>
<insert id="add" parameterType="com.learm.springboot.domain.entity.SysUser">
INSERT INTO sys_user
VALUES(#{userId},#{userName},#{age},#{email})
</insert>
<delete id="delete">
DELETE FROM sys_user
</delete>
</mapper>
新建 SysUserXmlMapper.java
文件
@Mapper
public interface SysUserXmlMapper {
int add(SysUser sysUser);
List<SysUser> getAll();
int delete();
}
新建测试类:
@SpringBootTest
public class XmlMapperTest {
@Autowired
private SysUserXmlMapper userMapper;
// JUnit5 开始 @Before 和@After被 @BeforeEach 和 @AfterEach给替代
@BeforeEach
public void setUp() {
testDelete();
}
@Test
public void test() {
testAdd();
testGetList();
}
private void testDelete() {
userMapper.delete();
List<SysUser> result = userMapper.getAll();
Assert.assertTrue(result.size() == 0);
}
private void testAdd() {
SysUser user = getOneUser();
int result = userMapper.add(user);
Assert.assertEquals(1, result);
}
private void testGetList() {
SysUser user = getOneUser();
List<SysUser> userList = userMapper.getAll();
Assert.assertTrue(userList.size() > 0);
Assert.assertEquals(user, userList.get(0));
}
private SysUser getOneUser() {
SysUser user = new SysUser();
user.setUserId(new Long("1572228567336"));
user.setUserName("MarkLogZhu");
user.setAge(26);
user.setEmail("marklogzhu@163.com");
return user;
}
}
1.4 两种方式选择
单表操作可以直接使用注解形式,多表操作采用 XML
形式。
二、通用 Mapper
2.1 为什么使用通用 Mapper
原生的 mybatis 就算最基本的单表 CRUD
也需要我们先手工生成大量的文件,如 pojo 类 、 mapper文件以及dao类 。Mybati 为了方便我们特地提供了 mybatis generator
工具来自动生成这些文件,而 通用 Mapper 是对mybatis generator
升级改造,解决了使用 mybatis-generator
可能需要大量重构的问题,并且在这个基础上加入了一些新的功能。 另一种改造方向的技术是 Mybatis-Plus, 它不仅能够根据数据库表快速生成 pojo 实体类,还封装了大量 CRUD 方法,使用 Wrapper 解决了复杂条件构造等问题,更是根据开发中常见的问题给出了一系列解决方案。
2.2 集成 通用 Mapper
导入依赖
<dependencies>
......
<!-- 通用 mybatis 依赖-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
</dependencies>
设置扫描注解
@SpringBootApplication
@MapperScan("com.learm.springboot")
public class SpringbootApplication extends SpringBootServletInitializer {
......
}
2.3 通用 Mapper 专用代码生成器
通用 Mapper 支持 Java 代码和插件两种形式生成文件,我们这边采用插件的形式。
1.在 pom.xml
文件中添加插件
<build>
<finalName>SpringBoot</finalName>
<plugins>
......
<!--通用 Mapper 代码生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<configurationFile>
${basedir}/src/main/resources/generator/generatorConfig.xml
</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.1.5</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-generator</artifactId>
<version>1.1.5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
2.在 resources/generator
目录下新建 generatorConfig.xml
文件
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--配置文件-->
<properties resource="generator/config.properties"/>
<context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
<property name="caseSensitive" value="true"/>
<!--增加 lombok 注解-->
<property name="lombok" value="Getter,Setter,ToString"/>
</plugin>
<!--数据库连接-->
<jdbcConnection driverClass="${jdbc.driverClass}"
connectionURL="${jdbc.url}"
userId="${jdbc.user}"
password="${jdbc.password}">
</jdbcConnection>
<!--实体-->
<javaModelGenerator targetPackage="${packageName}.domain.entity.${moduleName}"
targetProject="src/main/java"/>
<!--mapper.xml 文件-->
<sqlMapGenerator targetPackage="mybatis/mapper/${moduleName}"
targetProject="src/main/resources"/>
<!--mapper.Dao-->
<javaClientGenerator targetPackage="${packageName}.dao.${moduleName}"
targetProject="src/main/java"
type="XMLMAPPER"/>
<!--要生成的表-->
<table tableName="${tableName}">
<generatedKey column="id" sqlStatement="JDBC"/>
</table>
</context>
</generatorConfiguration>
3.在resources/generator
目录下新建 config.properties
文件
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true
jdbc.user=root
jdbc.password=sa000
packageName=com.learm.springboot
moduleName=system
tableName=sys_user
4.执行 Mavne 插件,生成文件
2.3 测试
@SpringBootTest
public class MapperTest {
@Autowired
private SysUserMapper sysUserMapper;
@Test
public void testAdd() {
SysUser user = new SysUser();
user.setUserId(new Long(new Date().getTime()));
user.setAge(25);
user.setUserName("lulu");
user.setEmail("lulu@163.com");
int result = sysUserMapper.insertSelective(user);
Assert.assertTrue(result > 0);
}
@Test
public void testSelectAll() {
List<SysUser> userList = sysUserMapper.selectAll();
Assert.assertNotNull(userList);
Assert.assertTrue(userList.size() > 0);
}
}