Spring Boot 集成 MyBatis

本文介紹了 Spring Boot 2.x 集成 MyBatis (3) 的開發(fā)過程。

MyBatis 是什么?
MyBatis 是一款優(yōu)秀的持久層框架,它支持定制化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設(shè)置參數(shù)以及獲取結(jié)果集。MyBatis 可以使用簡單的 XML 或注解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數(shù)據(jù)庫中的記錄。

MyBatis 官方網(wǎng)站 提供中文文檔,本文只介紹 Spring Boot 集成 MyBatis 的基礎(chǔ)配置和應(yīng)用,更多細節(jié)請參看官方文檔。

開發(fā)環(huán)境:
JDK 8
Maven 3.5
MySQL 5.6
IntelliJ IDEA (Version 2017.3.3)

1 在 IntelliJ IDEA 中新建 Spring Boot 工程,請參看

-> IntelliJ IDEA 創(chuàng)建 Spring Boot 工程

-> Spring Boot 單元測試

2 在 POM 文件中添加 mybatis-spring-boot-starter 依賴和 MySQL 驅(qū)動

<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 與傳統(tǒng)的 MyBatis 開發(fā)相比,MyBatis-Spring-Boot-Starter 預(yù)先做了很多的工作,官方描述如下

4 修改 application.properties (或 application.yml) 文件,配置 Spring Boot 工程數(shù)據(jù)源

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 工程中的基礎(chǔ)配置??梢灾志帉憯?shù)據(jù)訪問層代碼。

7 準備數(shù)據(jù)庫表

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 的實現(xiàn)類,MyBatis 可以根據(jù)定義的 Mapper 通過動態(tài)代理自動生成 DAO 接口對象,有關(guān) MyBatis 的實現(xiàn)細節(jié)不在此贅述,可以參考官方文檔

11 MyBatis 支持使用 Java Config 方式定義 SQL Mapper,也支持通過 XML 方式配置,因為實際開發(fā)過程中自定義 SQL 往往很長,這樣 XML 在格式化顯示 SQL 語句時比 Java Config 方式更清晰,建議優(yōu)先考慮 XML 定義 SQL Mapper。

12 因為自定義 SQL 語句過程中很可能出現(xiàn)筆誤或其它異常,所以建議先寫單元測試,再定義 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 的基礎(chǔ)配置和用法,有關(guān)批量插入、關(guān)聯(lián)查詢、動態(tài) SQL、存儲過程等內(nèi)容請參看 MyBatis 官方文檔和相關(guān)教程。

16 有關(guān) 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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容