一.前言
筆者在配置spring boot + mybatis的集成運行MySQL數據庫的時候,參閱了很多博文,發(fā)現大部分都是長篇大論的堆砌代碼,內容也是千篇一律,讓讀者晦澀難懂,不利于環(huán)境的快速搭建。于是,筆者在參考了這些博文之后,自己總結了一種相對簡單的配置方式。與其說是簡單的配置方式,不如說是簡單的描述方式,方便有需要的人快速配置spring boot + mybatis集成。
二.步驟
Mybatis的集成可以簡單地概括成兩步:
①application.properties增加spring配置數據庫鏈接地址
②pom.xml引入mybatis-spring-boot-starter和mysql-connector-java
當然啦,以上兩個步驟是建立在有spring boot項目的前提之下,下面開始詳細說明。
三.開始
①進入SPRING INITIALIZR(如圖1),輸入項目名稱,選擇要引入的依賴(Web,MySQL,Mybatis),最后生成項目下載到本地(如圖2)。

到此,我們相當于完成了章節(jié)二步驟的第②步,即引入了mybatis-spring-boot-starter和mysql-connector-java。
②進入IDEA,解壓上一步下載好的項目然后打開,如圖3,4所示。
③項目目錄結構
在這里只是象征性地模仿著某些blog貼出項目目錄結構,不作解釋。如圖5,值得注意的是,橙色圈出來的部分是筆者自己創(chuàng)建的目錄。紅色圈出的就是要配置的部分,對應于章節(jié)二的第①步,其中mybatis-config.xml是需要手動創(chuàng)建的。
④mybatis-config.xml配置文件
在resources目錄下手動創(chuàng)建mybatis-config.xml,復制粘貼以下代碼。
<?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>
<settings>
<!-- Globally enables or disables any caches configured in any mapper under this configuration -->
<setting name="cacheEnabled" value="true"/>
<!-- Sets the number of seconds the driver will wait for a response from the database -->
<setting name="defaultStatementTimeout" value="3000"/>
<!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- Allows JDBC support for generated keys. A compatible driver is required.
This setting forces generated keys to be used if set to true,
as some drivers deny compatibility but still work -->
<setting name="useGeneratedKeys" value="true"/>
</settings>
<!-- Continue going here -->
</configuration>
⑤application.properties配置
將以下配置拷貝至application.properties中。
#數據庫配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
mybatis.config-location=classpath:mybatis-config.xml
至此,已經完成了spring boot + mybatis的集成配置,最終的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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.st</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
四.定義映射器
雖然說spring boot簡化了很多Mybatis復雜的xml配置,但是作為Mybatis的四大組件之一的映射器是不可或缺的??梢赃@樣理解,一個映射器 = 一個接口 + 一個xml文件。
①準備工作
例如,筆者創(chuàng)建了一個名為“test”的數據庫,其中有一個“roommate”表,存放的是室友信息(可能我“愛”上了我的室友們吧,哈哈)。于是,我們需要創(chuàng)建一個roommate的POJO,Mybatis會自動完成數據庫表字段向POJO中屬性的映射。圖6是數據庫的“roommate”表結構,下面是與之對應的“Roommate.java”。

在項目目錄model中創(chuàng)建Roommate.java,如下。
package com.st.demo.model;
/**
* Created by songtao on 2018/8/21.
*/
public class Roommate {
private String name;
private int sex;
private String phone;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Roommate{" +
"name='" + name + '\'' +
", sex=" + (sex == 1 ? "男" : "女") +
", phone='" + phone + '\'' +
", age=" + age +
'}';
}
}
②定義RoommateDAO接口
在dao目錄中創(chuàng)建RoommateDAO接口,為了簡單演示,這里只是做了一個按id查詢的操作。注意不要忘了@Mapper,因為要在IoC容器初始化。
tips:其實這里可以直接在getRoommateById()方法上方使用@Select({"select name,sex,phone,age from roommate where id = #{id}"}),但是筆者在閱讀《Java EE互聯網輕量級框架整合開發(fā) SSM框架》一書中,作者提到,要采用xml配置的方式為主,注解的方式為輔。試想一下,當sql語句很復雜的時候,用注解的方式會很容易出錯,還會導致代碼的可讀性降低。于是,筆者采用了xml配置的方式。
至此,一個接口定義完了,接下來定義一個xml。
package com.st.demo.dao;
import org.apache.ibatis.annotations.Mapper;
import com.st.demo.model.Roommate;
/**
* Created by songtao on 2018/8/21.
*/
@Mapper
public interface RoommateDAO {
Roommate getRoommateById(int id);
}
③定義RoommateDAO.xml
xml配置的原則:在相同的包目錄下定義同名xml。
這里有兩點需要注意:a.相同的包 b.同名xml。
這里我們再看一下目錄結構,如圖7。
紅色線條部分體現了相同的包。這里還要注意:在resources下創(chuàng)建目錄的時候不可以一次性把目錄創(chuàng)建成com.st.demo.dao,要先創(chuàng)建com目錄,然后在com目錄中創(chuàng)建st目錄,再往st目錄創(chuàng)建demo目錄,最后在demo目錄中創(chuàng)建dao目錄。
橙色標記部分體現了同名,即RoommateDAO和RoommateDAO.xml同名。

以下是RoommateDAO.xml的內容。注意:namespace的值要和上一步定義的接口RoommateDAO一致(全名),<select>標簽中的id的值要與RoommateDAO中的方法getRoommateById()一致,resultType要和getRoommateById()方法的返回值Roommate一致,并且要用類全名。
<?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.st.demo.dao.RoommateDAO">
<sql id="table">roommate</sql>
<sql id="selectFields">name,sex,phone,age</sql>
<select id="getRoommateById" resultType="com.st.demo.model.Roommate">
SELECT
<include refid="selectFields"/>
FROM
<include refid="table"/>
WHERE
id = #{id}
</select>
</mapper>
到此,映射器已經定義完畢了,接下來就是激動人心的時刻了,能不能取得數據呢,下節(jié)見分曉。
五.測試
在/src/test/java/com/st/demo路徑中新建一個測試類DBTest.java,先用@Autowired將按RoommateDAO類型注入roommateDAO,然后調用getRoommateById()方法查詢id為'1'的數據,運行結果如圖8。
package com.st.demo;
import com.st.demo.dao.RoommateDAO;
import com.st.demo.model.Roommate;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Created by songtao on 2018/8/21.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class DBTest {
@Autowired
RoommateDAO roommateDAO;
@Test
public void testDB(){
Roommate roommate = roommateDAO.getRoommateById(1);
System.out.println(roommate.toString());
}
}

六.小結
數據庫在開發(fā)過程中充當著重要的角色,框架的出現抹去了以往JDBC操作數據庫的紛繁。傳統(tǒng)的JDBC的數據庫操作步驟為:①加載驅動 ②創(chuàng)建數據庫連接 ③創(chuàng)建statement對象 ④執(zhí)行SQL獲取數據 ⑤數據轉換 ⑥資源釋放。而Mybatis關注第④步。(以上來自葉神的總結)。于是在如此流行的后臺框架Spring boot集成Mybatis也是大勢所趨了,本文旨在以最簡單的方式描述配置過程,邁出開發(fā)的這一小步。以上都是來自筆者個人的經驗總結,如有疏漏,歡迎批評指正。
七.參考鏈接
1.https://start.spring.io/
2.http://spring.io/projects/spring-boot
3.http://www.mybatis.org/mybatis-3/zh/index.html