SpringBoot+Mybatis實現(xiàn)Mapper接口與Sql綁定幾種姿勢
通常我們在使用Mybatis進(jìn)行開發(fā)時,會選擇xml文件來寫對應(yīng)的sql,然后將Mapper接口與sql的xml文件建立綁定關(guān)系,然后在項目中調(diào)用mapper接口就可以執(zhí)行對應(yīng)的sql
那么如何將Mapper接口與sql進(jìn)行綁定呢?本文將介紹四種常見的姿勢
- 默認(rèn)策略
- SpringBoot配置參數(shù)mybatis.mapper-locations
- <mapper>指定
- SqlSessionFactory指定
I. 環(huán)境準(zhǔn)備
1. 數(shù)據(jù)庫準(zhǔn)備
使用mysql作為本文的實例數(shù)據(jù)庫,新增一張表
CREATE TABLE `money` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL DEFAULT '' COMMENT '用戶名', `money` int(26) NOT NULL DEFAULT '0' COMMENT '錢', `is_deleted` tinyint(1) NOT NULL DEFAULT '0', `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時間', `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間', PRIMARY KEY (`id`), KEY `name` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
2. 項目環(huán)境
本文借助 SpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEA進(jìn)行開發(fā)
pom依賴如下
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
db配置信息 application.yml
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password:
II. 實例演示
環(huán)境搭建完畢,準(zhǔn)備對應(yīng)的實體類,Mapper接口
1. 實體類,Mapper接口
數(shù)據(jù)庫實體類: MoneyPo
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MoneyPo {
private Integer id;
private String name;
private Long money;
private Integer isDeleted;
private Timestamp createAt;
private Timestamp updateAt;
}
一個基礎(chǔ)的Mapper接口
@Mapper
public interface MoneyMapper {
trueint savePo(@Param("po") MoneyPo po);
}
一個demo service
@Repository
public class MoneyRepository {
private Random random = new Random();
public void testMapper() {
MoneyPo po = new MoneyPo();
po.setName("mybatis user");
po.setMoney((long) random.nextInt(12343));
po.setIsDeleted(0);
moneyMapper.savePo(po);
System.out.println("add record: " + po);
}
2. sql文件
寫sql的xml文件內(nèi)容如下
<?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.git.hui.boot.mybatis.mapper.MoneyMapper">
<insert id="savePo" parameterType="com.git.hui.boot.mybatis.entity.MoneyPo" useGeneratedKeys="true"
keyProperty="po.id">
INSERT INTO `money` (`name`, `money`, `is_deleted`)
VALUES
true (#{po.name}, #{po.money}, #{po.isDeleted});
</insert>
</mapper>
3. Mapper與Sql綁定
以上為代碼層面實現(xiàn)CURD的基礎(chǔ)知識,基本上就是mybatis操作的那些套路,沒有什么需要特殊注意的;接下來我們進(jìn)入本文主題
如何告訴mybatis,將上面的MoenyMapper接口與xml文件關(guān)聯(lián)起來
3.1 默認(rèn)方式
采用默認(rèn)的綁定方式,不需要我們做額外的操作,重點(diǎn)是需要遵循規(guī)則
- xml的目錄結(jié)構(gòu),與Mapper接口的包路徑完全一致
- xml文件名與Mapper接口名完全一致(注意大小寫都要完全一致)
請注意上面的另個完全一致

使用默認(rèn)的方式進(jìn)行綁定時,一個示例如上圖;特別需要注意的是文件名的大小寫,xml文件的目錄層級都需要完全一致
如果使用上面這種方式,在執(zhí)行時,依然提示有問題,排查的思路就是查看 target目錄下生成的class文件與xml文件是否在一起,如下圖就是正常的case

再次說明
基于上面的case,我們可以直接將xml文件,與mapper接口寫在一起,不放在資源路徑resources下面
3.2 SpringBoot配置
SpringBoot提供了一個簡單的配置,來指定Mapper接口與sql的綁定,一行配置即可
mybatis: mapper-locations: classpath:sqlmapper/*.xml
使用這種方式就比較簡單了,不要求xml文件與Mapper接口文件名一致;也沒有指定路徑層級一致

3.3 Mapper標(biāo)簽
mapper標(biāo)簽,需要放在mybatis的配置文件中,因此我們首先通過SpringBoot的配置參數(shù)指定文件路徑
mybatis:
configuration:
config-location: classpath:mybatis-config.xml
在資源文件下,新建文件 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//ibatis.apache.org//DTD Config 3.1//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper resource="sqlmapper/money-mapper.xml"/>
</mappers>
</configuration>
通過上面的mapper標(biāo)簽來指定注冊關(guān)系,也是可行的,詳情可參考官方文檔 !
https://mybatis.org/mybatis-3/configuration.html#mappers
3.4 SqlSessionFactory
在前面一篇介紹Mapper接口注冊的博文中,就介紹了通過qlSessionFactory+ MapperScannerConfigurer來注冊
這里也是可以通過SqlSessionFactory來指定xml文件的
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(
// 設(shè)置mybatis的xml所在位置,這里使用mybatis注解方式,沒有配置xml文件
new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/*.xml"));
// 注冊typehandler,供全局使用
bean.setTypeHandlers(new Timestamp2LongHandler());
bean.setPlugins(new SqlStatInterceptor());
return bean.getObject();
}
4. 小結(jié)
本文主要介紹了四種Mapper接口與sql文件關(guān)系綁定的姿勢,了解幾種不同的姿勢的特點(diǎn),在實際的項目開發(fā)中,選擇一個即可
- 默認(rèn):在resource資源目錄下,xml文件的目錄層級與Mapper接口的包層級完全一致,且xml文件名與mapper接口文件名也完全一致
- 如mapper接口: com.git.hui.boot.mybatis.mapper.MoneyMapper
- 對應(yīng)的xml文件: com/git/hui/boot/mybatis/mapper/MoneyMapper.xml
- springboot配置參數(shù):
- application.yml配置文件中,指定 mybatis.mapper-locations=classpath:sqlmapper/*.xml
- mybatis-config配置文件
- 這種姿勢常見于非SpringBoot項目集成mybatis,通常將mybatis的相關(guān)配置放在 mybatis-config.xml 文件中
- 首先在配置文件中,指定加載參數(shù) mybatis.config-location=classpath:mybatis-config.xml
- 然后指定映射器 <mappers><mapper resource="sqlmapper/money-mapper.xml"/></mappers>
- SqlSessionFactory指定
- 直接在SqlSessionFactory中指定即可Mapper文件
// 設(shè)置mybatis的xml所在位置,這里使用mybatis注解方式,沒有配置xml文件
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/*.xml"));
除了上面幾種方式之外,mybatis還支持無xml的方式,完全依靠注解來實現(xiàn)sql的拼裝,因此也就不存在映射關(guān)系綁定了,關(guān)于注解的case,可以參考博文【DB系列】Mybatis+注解整合篇
III. 不能錯過的源碼和相關(guān)知識點(diǎn)
項目
工程:https://github.com/liuyueyi/spring-boot-demo
源碼:https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/104-mybatis-ano
源碼:https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/103-mybatis-xml
到此這篇關(guān)于SpringBoot+Mybatis實現(xiàn)Mapper接口與Sql綁定幾種姿勢的文章就介紹到這了,更多相關(guān)SpringBoot Mybatis Mapper接口與Sql綁定內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot使用logback自定義日志的詳細(xì)過程
這篇文章主要介紹了springboot使用logback自定義日志的詳細(xì)過程,本文通過實例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2024-12-12
springboot集成opencv實現(xiàn)人臉識別功能的詳細(xì)步驟
大家都知道OpenCV是一個基于BSD許可(開源)發(fā)行的跨平臺計算機(jī)視覺和機(jī)器學(xué)習(xí)軟件庫,可以運(yùn)行在Linux、Windows、Android和Mac OS操作系統(tǒng)上今天通過本文給大家分享springboot集成opencv實現(xiàn)人臉識別,感興趣的朋友一起看看吧2021-06-06
Win10系統(tǒng)下配置java環(huán)境變量的全過程
這篇文章主要給大家介紹了關(guān)于Win10系統(tǒng)下配置java環(huán)境變量的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
Java對象Serializable接口實現(xiàn)詳解
這篇文章主要介紹了Java對象Serializable接口實現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-12-12
Java中static修飾的靜態(tài)變量、方法及代碼塊的特性與使用
這篇文章主要介紹了Java中static修飾的靜態(tài)變量、方法及代碼塊的特性與使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
SpringMVC?HttpMessageConverter報文信息轉(zhuǎn)換器
這篇文章主要為大家介紹了SpringMVC?HttpMessageConverter報文信息轉(zhuǎn)換器,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
myeclipse開發(fā)servlet_動力節(jié)點(diǎn)Java學(xué)院整理
MyEclipse,是在eclipse基礎(chǔ)上加上自己的插件開發(fā)而成的功能強(qiáng)大的企業(yè)級集成開發(fā)環(huán)境,主要用于Java、Java EE以及移動應(yīng)用的開發(fā)。下面這篇文章主要給大家介紹了關(guān)于myeclipse開發(fā)servlet的相關(guān)資料,需要的朋友可以參考下。2017-07-07

