本文介绍了 Spring Boot 2.x 集成 MyBatis (3) 的开发过程。
MyBatis 是什么?
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
MyBatis 官方网站 提供中文文档,本文只介绍 Spring Boot 集成 MyBatis 的基础配置和应用,更多细节请参看官方文档。
开发环境:
JDK 8
Maven 3.5
MySQL 5.6
IntelliJ IDEA (Version 2017.3.3)
1 在 IntelliJ IDEA 中新建 Spring Boot 工程,请参看
-> IntelliJ IDEA 创建 Spring Boot 工程
2 在 POM 文件中添加 mybatis-spring-boot-starter 依赖和 MySQL 驱动
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
3 与传统的 MyBatis 开发相比,MyBatis-Spring-Boot-Starter 预先做了很多的工作,官方描述如下
4 修改 application.properties (或 application.yml) 文件,配置 Spring Boot 工程数据源
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=true
username: root
password: 123456
5 修改 application.properties (或 application.yml) 文件,配置 MyBatis 映射(Mapper)文件目录
mybatis:
mapper-locations: mybatis-mapper/*.xml
6 至此,已完成 MyBatis 在 Spring Boot 工程中的基础配置。可以着手编写数据访问层代码。
7 准备数据库表
CREATE TABLE `test`.`user` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`account` VARCHAR(30) NOT NULL,
`name` VARCHAR(60) NOT NULL,
`birth` DATE NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC),
UNIQUE INDEX `account_UNIQUE` (`account` ASC));
8 编写 DO / PO (Data Object / Persistence Object)
package demo.spring.boot.transaction.domain;
import java.time.LocalDate;
import java.util.Objects;
public class User {
private Long id;
private String account;
private String name;
private LocalDate birth;
public User() {
}
public User(String account, String name, LocalDate birth) {
this.account = account;
this.name = name;
this.birth = birth;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getBirth() {
return birth;
}
public void setBirth(LocalDate birth) {
this.birth = birth;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", account='" + account + '\'' +
", name='" + name + '\'' +
", birth=" + birth +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(id, user.id) &&
Objects.equals(account, user.account) &&
Objects.equals(name, user.name) &&
Objects.equals(birth, user.birth);
}
@Override
public int hashCode() {
return Objects.hash(id, account, name, birth);
}
}
9 编写 DAO 接口
package demo.spring.boot.transaction.dao;
import demo.spring.boot.transaction.domain.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserDao {
int insert(User user);
User get(Long id);
int update(User user);
int delete();
}
10 使用 MyBatis 不需要编写 DAO 的实现类,MyBatis 可以根据定义的 Mapper 通过动态代理自动生成 DAO 接口对象,有关 MyBatis 的实现细节不在此赘述,可以参考官方文档
11 MyBatis 支持使用 Java Config 方式定义 SQL Mapper,也支持通过 XML 方式配置,因为实际开发过程中自定义 SQL 往往很长,这样 XML 在格式化显示 SQL 语句时比 Java Config 方式更清晰,建议优先考虑 XML 定义 SQL Mapper。
12 因为自定义 SQL 语句过程中很可能出现笔误或其它异常,所以建议先写单元测试,再定义 SQL Mapper。下面给出增删改查的单元测试代码示例。
package demo.spring.boot.transaction;
import demo.spring.boot.transaction.dao.UserDao;
import demo.spring.boot.transaction.domain.User;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.LocalDate;
@RunWith(SpringRunner.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class UserDaoTests {
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Autowired
private UserDao userDao;
@Test
public void test1Insert() {
User user = new User();
user.setAccount("initial");
user.setName("Test Insert User");
user.setBirth(LocalDate.of(1985, 1, 1));
int insertRowNum = userDao.insert(user);
Assert.assertEquals(1, insertRowNum);
Assert.assertTrue(user.getId() > 0);
}
@Test
public void test2Get() {
User user = new User("for_get", "Test Get User", LocalDate.of(1990, 12, 31));
userDao.insert(user);
User result = userDao.get(user.getId());
Assert.assertNotNull(user);
Assert.assertEquals(user, result);
}
@Test
public void test3Update() {
User user = new User("for_update", "Test Update User", LocalDate.of(1995, 6, 30));
userDao.insert(user);
user.setAccount("updated");
user.setName("Updated Name");
user.setBirth(LocalDate.of(1990, 12, 31));
Assert.assertEquals(1, userDao.update(user));
Assert.assertEquals(user, userDao.get(user.getId()));
}
@Test
public void test4Delete() {
User user = new User("for_delete", "Test Delete User", LocalDate.of(1995, 6, 30));
userDao.insert(user);
int deleteRowsNum = userDao.delete();
Assert.assertTrue(deleteRowsNum > 0);
}
}
13 定义 SQL Mapper
<?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="demo.spring.boot.transaction.dao.UserDao">
<insert id="insert" parameterType="demo.spring.boot.transaction.domain.User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO `user`
(`account`, `name`, `birth`)
VALUES
(#{account}, #{name}, #{birth})
</insert>
<select id="get" parameterType="_long" resultType="demo.spring.boot.transaction.domain.User">
SELECT `id`, `account`, `name`, `birth`
FROM `user`
WHERE `id` = #{id}
</select>
<update id="update" parameterType="demo.spring.boot.transaction.domain.User">
UPDATE `user`
SET `account` = #{account}, `name` = #{name}, `birth` = #{birth}
WHERE `id` = #{id}
</update>
<delete id="delete">
DELETE FROM `user`
</delete>
</mapper>
14 运行单元测试
15 本文只介绍了 Spring Boot 工程中集成 MyBatis 的基础配置和用法,有关批量插入、关联查询、动态 SQL、存储过程等内容请参看 MyBatis 官方文档和相关教程。
16 有关 MyBatis-Spring-Boot-Starter 的更多信息请参看 mybatis-spring-boot-autoconfigure
附
工程目录
POM
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>demo.spring.boot</groupId>
<artifactId>demo-spring-boot-transaction</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo-spring-boot-transaction</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<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>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置文件 application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=true
username: root
password: 123456
mybatis:
mapper-locations: mybatis-mapper/*.xml