Springboot 整合 Mybatis 的完整 Web 案例

摘要: 原創出處:www.bysocket.com 泥瓦匠BYSocket 希望轉載,保留摘要,謝謝!
推薦一本書《 騰訊傳》。
新年第一篇 Springboot 技術文誕生。泥瓦匠準備寫寫 Springboot 相關最佳實踐。一方面總結下一些 Springboot 相關,一方面和大家交流交流 Springboot 框架。
現在業界互聯網流行的數據操作層框架 Mybatis,下面詳解下 Springboot 如何整合 Mybatis ,這邊沒有使用 Mybatis Annotation 這種,是使用 xml 配置 SQL。因爲我覺得 SQL 和業務代碼應該隔離,方便和 DBA 校對 SQL。二者 XML 對較長的 SQL 比較清晰。

一、運行 springboot-mybatis 工程

git clone 下載工程  springboot-learning-example ,項目地址見  GitHub。下面開始運行工程步驟(Quick Start):
1.數據庫準備
a.創建數據庫 springbootdb:
1
CREATE DATABASE springbootdb;
b.創建表 city :(因爲我喜歡徒步)
1
2
3
4
5
6
7
8
DROP TABLE IF EXISTS  `city`;
CREATE TABLE `city` (
   ` id ` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '城市編號' ,
   `province_id` int(10) unsigned  NOT NULL COMMENT '省份編號' ,
   `city_name` varchar(25) DEFAULT NULL COMMENT '城市名稱' ,
   `description` varchar(25) DEFAULT NULL COMMENT '描述' ,
   PRIMARY KEY (` id `)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
c.插入數據
1
INSERT city VALUES (1 ,1, '溫嶺市' , 'BYSocket 的家在溫嶺。' );
2. 項目結構介紹
項目結構如下圖所示:
org.spring.springboot.controller – Controller 層
org.spring.springboot.dao – 數據操作層 DAO
org.spring.springboot.domain – 實體類
org.spring.springboot.service – 業務邏輯層
Application – 應用啓動類
application.properties – 應用配置文件,應用啓動會自動讀取配置
3.改數據庫配置
打開 application.properties 文件, 修改相應的數據源配置,比如數據源地址、賬號、密碼等。(如果不是用 MySQL,自行添加連接驅動 pom,然後修改驅動名配置。)
4.編譯工程
在項目根目錄 springboot-learning-example,運行 maven 指令:
1
mvn clean install
5.運行工程

右鍵運行 Application 應用啓動類的 main 函數,然後在瀏覽器訪問:

1
http: //localhost :8080 /api/city ?cityName=溫嶺市
可以看到返回的 JSON 結果:
1
2
3
4
5
6
{
    "id" : 1,
    "provinceId" : 1,
    "cityName" : "溫嶺市" ,
    "description" : "我的家在溫嶺。"
}
如圖:

二、springboot-mybatis 工程配置詳解

1.pom 添加 Mybatis 依賴
1
2
3
4
5
6
<!-- Spring Boot Mybatis 依賴 -->
<dependency>
    <groupId>org.mybatis.spring.boot< /groupId >
    <artifactId>mybatis-spring-boot-starter< /artifactId >
    <version>${mybatis-spring-boot}< /version >
< /dependency >
mybatis-spring-boot-starter 工程依賴如圖:
2.在 application.properties 應用配置文件,增加 Mybatis 相關配置
1
2
3
## Mybatis 配置
mybatis.typeAliasesPackage=org.spring.springboot.domain
mybatis.mapperLocations=classpath:mapper/*.xml
mybatis.typeAliasesPackage 配置爲 org.spring.springboot.domain,指向實體類包路徑。mybatis.mapperLocations 配置爲 classpath 路徑下 mapper 包下,* 代表會掃描所有 xml 文件。
mybatis 其他配置相關詳解如下:
mybatis.config = mybatis 配置文件名稱
mybatis.mapperLocations = mapper xml 文件地址
mybatis.typeAliasesPackage = 實體類包路徑
mybatis.typeHandlersPackage = type handlers 處理器包路徑
mybatis.check-config-location = 檢查 mybatis 配置是否存在,一般命名爲 mybatis-config.xml
mybatis.executorType = 執行模式。默認是 SIMPLE
3.在 Application 應用啓動類添加註解 MapperScan
Application.java 代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
  * Spring Boot 應用啓動類
  *
  * Created by bysocket on 16 /4/26 .
  */
// Spring Boot 應用的標識
@SpringBootApplication
// mapper 接口類掃描包配置
@MapperScan( "org.spring.springboot.dao" )
public class Application {
 
    public static void main(String[] args) {
        // 程序啓動入口
        // 啓動嵌入式的 Tomcat 並初始化 Spring 環境及其各 Spring 組件
        SpringApplication.run(Application.class,args);
    }
}
mapper 接口類掃描包配置註解 MapperScan :用這個註解可以註冊 Mybatis mapper 接口類。
4.添加相應的 City domain類、CityDao mapper接口類

City.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
  * 城市實體類
  *
  * Created by bysocket on 07 /02/2017 .
  */
public class City {
 
     /**
      * 城市編號
      */
     private Long id ;
 
     /**
      * 省份編號
      */
     private Long provinceId;
 
     /**
      * 城市名稱
      */
     private String cityName;
 
     /**
      * 描述
      */
     private String description;
 
     public Long getId() {
         return id ;
     }
 
     public void setId(Long id ) {
         this. id = id ;
     }
 
     public Long getProvinceId() {
         return provinceId;
     }
 
     public void setProvinceId(Long provinceId) {
         this.provinceId = provinceId;
     }
 
     public String getCityName() {
         return cityName;
     }
 
     public void setCityName(String cityName) {
         this.cityName = cityName;
     }
 
     public String getDescription() {
         return description;
     }
 
     public void setDescription(String description) {
         this.description = description;
     }
}
CityDao.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
  * 城市 DAO 接口類
  *
  * Created by bysocket on 07 /02/2017 .
  */
public interface CityDao {
 
     /**
      * 根據城市名稱,查詢城市信息
      *
      * @param cityName 城市名
      */
     City findByName(@Param( "cityName" ) String cityName);
}
其他不明白的,可以 git clone 下載工程  springboot-learning-example ,工程代碼註解很詳細。  https://github.com/JeffLi1993/springboot-learning-example

三、其他

利用 Mybatis-generator自動生成代碼  http://www.cnblogs.com/yjmyzz/p/4210554.html
Mybatis 通用 Mapper3  https://github.com/abel533/Mapper
Mybatis 分頁插件 PageHelper  https://github.com/pagehelper/Mybatis-PageHelper
最後,推薦閱讀:《  Spring Boot 之 HelloWorld 詳解
歡迎掃一掃我的公衆號關注 — 及時得到博客訂閱哦!
— http://www.bysocket.com/ —
— https://github.com/JeffLi1993 —