1. 程式人生 > 實用技巧 >Spring Boot 整合 MyBatis

Spring Boot 整合 MyBatis

建立 Spring Boot 專案

利用 IDEA 內建的 Spring Initializr 建立專案,根據需要選擇相應的模組,這裡已經內建了 MyBatis Framework 選項。

當然你也可以選擇手動引入:

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>

另外不要忘了引入資料庫驅動的依賴。

專案 pom.xml 如下:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yin</groupId>
    <artifactId>boot-07-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>boot-07-mybatis</name>
    <description>Spring Boot 整合 MyBatis</description>

    <properties>
        <java.version>11</java.version>
        <mysql.version>8.0.19</mysql.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor
                            </artifactId>
                        </exclude>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

在 application.yml 中進行相關屬性的配置:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/jdbc_template?serverTimezone=Asia/Shanghai
    username: root
    password: 123456

mybatis:
  configuration:
    # 開啟駝峰命名自動對映
    map-underscore-to-camel-case: true
  # mapper 對映檔案位置
  mapper-locations: classpath:mapper/*.xml

spring.datasource 配置的是資料庫的相關屬性。

關於 MyBatis 的設定,這裡是在 mybatis.configuration 配置的。當然也可以編寫 MyBatis 的 xml 全域性配置檔案,並用mybatis.config-location 指定其位置,兩者二選一。

建立資料庫表

CREATE TABLE city
(
  `id`      INT(11) PRIMARY KEY AUTO_INCREMENT,
  `name`    VARCHAR(30),
  `state`   VARCHAR(30),
  `country` VARCHAR(30)
);

對應實體類:

@Data
public class City {
    private Long id;
    private String name;
    private String state;
    private String country;
}

編寫 mapper 介面

這裡以查詢和插入方法為例。在方法上直接標註相應的註解,然後編寫 SQL 語句即可,非常簡單方便。

不要忘記在類上標註 @Mapper 註解,表明這是一個 mapper 介面。

@Mapper
@Repository
public interface CityMapper {
    /*
      簡單的SQL直接註解搞定,複雜的SQL在xml中編寫
     */
    /**
     * 根據id查詢city
     *
     * @param id id
     * @return 查詢到的city
     */
    @Select("select id, name, state, country from city where id=#{id}")
    City getCityById(Long id);

    /**
     * 插入一條city記錄
     *
     * @param city 要插入的city
     */
    @Insert("insert into city(name, state, country) values(#{name},#{name},#{name})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(City city);
}

在方法註解上編寫 SQL 語句適合比較簡單的情況,如果遇到複雜 SQL,還是在 xml 檔案中編寫更好。以上面的 insert 方法為例,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.yin.mybatis.mapper.CityMapper">
    <!--void insert(City city); xml 配置版-->
    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        insert into city(name, state, country) values(#{name},#{name},#{name})
    </insert>
</mapper>

更復雜的 SQL 等的編寫屬於 MyBatis 的內容,不再贅述。

測試

經過上述操作,已經整合完成了,幾乎沒有編寫煩人的 xml 檔案。下面就可以對其進行測試了。

首先編寫 service:

@Service
public class CityService {
    @Autowired
    CityMapper cityMapper;

    public City getCityById(Long id) {
        return cityMapper.getCityById(id);
    }

    public void insert(City city) {
        cityMapper.insert(city);
    }
}

再編寫 controller:

@Controller
public class MybatisController {
    @Autowired
    CityService cityService;

    @ResponseBody
    @GetMapping("/city")
    public City getCityById(@RequestParam("id") Long id) {
        return cityService.getCityById(id);
    }

    @ResponseBody
    @PostMapping("/city")
    public City insertCity(City city) {
        cityService.insert(city);
        return city;
    }
}

測試工具使用 Postman。

測試前先看一下專案結構:

小鳥的圖示是 IDE 外掛 MyBatisX。

首先測試 getCityById 方法:

再來測試 insert 方法:


更多內容可參閱 MyBatis 官方資料:MyBatis integration with Spring Boot

本文程式碼已上傳至:https://gitee.com/ME_WE/spring-boot-practice