Mybatis開發(fā)團(tuán)隊(duì)為Spring Boot 提供了MyBatis-Spring-Boot-Starter方便使用织中。
要使用MyBatis-Spring-Boot-Starter模塊空凸,只需要在類路徑中包含?
mybatis-spring-boot-autoconfigure.jar文件及其依賴項(xiàng)(mybatis.jar诅蝶,mybatis?-spring.jar等) 。
下面介紹的是我用到的一部分功能我碟,全部功能還請查閱官方文檔
一、使用
如果您正在使用Maven,只需將以下依賴項(xiàng)添加到您的pom.xml中:
org.mybatis.spring.bootmybatis-spring-boot-starter2.0.0-SNAPSHOT
版本自己可選:
需要注意的是:在Spring 中使用mybatis 最少需要 一個SqlSessionFactory 和 mapper 接口
引入MyBatis-Spring-Boot-Starter?模塊后 將自動提供以
下功能
自動檢測現(xiàn)有的數(shù)據(jù)源秕衙。
將創(chuàng)建并注冊一個SqlSessionFactory的實(shí)例,使用SqlSessionFactoryBean作為輸入傳遞該DataSource僵刮。
將創(chuàng)建并注冊SqlSessionFactory的SqlSessionTemplate實(shí)例据忘。
自動掃描您的“Mapper”,將它們鏈接到SqlSessionTemplate并將它們注冊到Spring上下文搞糕,以便將它們注入到bean中勇吊。
就是說,使用了該Starter之后窍仰,只需要定義一個DataSource即可汉规,它會自動創(chuàng)建使用該DataSource的SqlSessionFactoryBean以及SqlSessionTemplate,會自動掃描你的Mappers驹吮,連接到SqlSessionTemplate针史,并注冊到Spring上下文中。
二 碟狞、配置
與其他Spring Boot應(yīng)用程序一樣啄枕,MyBatis-Spring-Boot-Application配置參數(shù)存儲在application.properties(或application.yml)內(nèi)部。使用前綴 mybatis
可用的屬性有:
config-location :MyBatis. xml配置文件的位置族沃。
check-config-location:?指示是否執(zhí)行MyBatis .xml配置文件的存在檢查
mapper-locations:Mapper.?xml配置文件的位置频祝。
type-aliases-package :?一般是放在model(或?qū)嶓w類)?上 泌参,別名替換,默認(rèn)是去掉包名常空。
type-handlers-package:用于搜索類型處理程序的包所在位置
configuration-properties:MyBatis配置的外部化屬性及舍。 指定的屬性可以用作MyBatis配置文件和Mapper文件的占位符。
configuration:一個MyBatis配置bean窟绷。 關(guān)于可用的屬性锯玛,請參閱MyBatis參考頁面。 注意此屬性不能與配置位置(config-location)同時使用兼蜈。
?紅色標(biāo)注為常用屬性
例:
# application.propertiesmybatis.type-aliases-package=com.example.domain.modelmybatis.type-handlers-package=com.example.typehandlermybatis.configuration.map-underscore-to-camel-case=truemybatis.configuration.default-fetch-size=100mybatis.configuration.default-statement-timeout=30
三攘残、真實(shí)使用過程
1、pom中引入?MyBatis-Spring-Boot-Starter
org.mybatis.spring.bootmybatis-spring-boot-starter2.0.0-SNAPSHOT
2为狸、配置數(shù)據(jù)源
直接在application.properties 中
3韭邓、在application.properties 中配置Mapper.xml 的掃描
4含滴、編寫Mapper接口蛋欣,和Mapper.xml
Mapper 接口要加@Mapper?注解
MyBatis-Spring-Boot-Starter將默認(rèn)搜索標(biāo)記有@Mapper注解的映射器秕噪。
您可能需要指定自定義注解或標(biāo)記界面進(jìn)行掃描。 如果是這樣漾根,你必須使用@MapperScan注解泰涂。
默認(rèn)不用加這個注解