SpringBoot+Mybatis實現(xiàn)Mapper接口與Sql綁定幾種姿勢
通常我們在使用Mybatis進行開發(fā)時,會選擇xml文件來寫對應的sql,然后將Mapper接口與sql的xml文件建立綁定關系,然后在項目中調用mapper接口就可以執(zhí)行對應的sql
那么如何將Mapper接口與sql進行綁定呢?本文將介紹四種常見的姿勢
- 默認策略
- SpringBoot配置參數(shù)mybatis.mapper-locations
- <mapper>指定
- SqlSessionFactory指定
I. 環(huán)境準備
1. 數(shù)據(jù)庫準備
使用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進行開發(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)境搭建完畢,準備對應的實體類,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;
}
一個基礎的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文件內容如下
<?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的基礎知識,基本上就是mybatis操作的那些套路,沒有什么需要特殊注意的;接下來我們進入本文主題
如何告訴mybatis,將上面的MoenyMapper接口與xml文件關聯(lián)起來
3.1 默認方式
采用默認的綁定方式,不需要我們做額外的操作,重點是需要遵循規(guī)則
- xml的目錄結構,與Mapper接口的包路徑完全一致
- xml文件名與Mapper接口名完全一致(注意大小寫都要完全一致)
請注意上面的另個完全一致

使用默認的方式進行綁定時,一個示例如上圖;特別需要注意的是文件名的大小寫,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標簽
mapper標簽,需要放在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標簽來指定注冊關系,也是可行的,詳情可參考官方文檔 !
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(
// 設置mybatis的xml所在位置,這里使用mybatis注解方式,沒有配置xml文件
new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/*.xml"));
// 注冊typehandler,供全局使用
bean.setTypeHandlers(new Timestamp2LongHandler());
bean.setPlugins(new SqlStatInterceptor());
return bean.getObject();
}
4. 小結
本文主要介紹了四種Mapper接口與sql文件關系綁定的姿勢,了解幾種不同的姿勢的特點,在實際的項目開發(fā)中,選擇一個即可
- 默認:在resource資源目錄下,xml文件的目錄層級與Mapper接口的包層級完全一致,且xml文件名與mapper接口文件名也完全一致
- 如mapper接口: com.git.hui.boot.mybatis.mapper.MoneyMapper
- 對應的xml文件: com/git/hui/boot/mybatis/mapper/MoneyMapper.xml
- springboot配置參數(shù):
- application.yml配置文件中,指定 mybatis.mapper-locations=classpath:sqlmapper/*.xml
- mybatis-config配置文件
- 這種姿勢常見于非SpringBoot項目集成mybatis,通常將mybatis的相關配置放在 mybatis-config.xml 文件中
- 首先在配置文件中,指定加載參數(shù) mybatis.config-location=classpath:mybatis-config.xml
- 然后指定映射器 <mappers><mapper resource="sqlmapper/money-mapper.xml"/></mappers>
- SqlSessionFactory指定
- 直接在SqlSessionFactory中指定即可Mapper文件
// 設置mybatis的xml所在位置,這里使用mybatis注解方式,沒有配置xml文件
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/*.xml"));
除了上面幾種方式之外,mybatis還支持無xml的方式,完全依靠注解來實現(xiàn)sql的拼裝,因此也就不存在映射關系綁定了,關于注解的case,可以參考博文【DB系列】Mybatis+注解整合篇
III. 不能錯過的源碼和相關知識點
項目
工程: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
到此這篇關于SpringBoot+Mybatis實現(xiàn)Mapper接口與Sql綁定幾種姿勢的文章就介紹到這了,更多相關SpringBoot Mybatis Mapper接口與Sql綁定內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
淺談關于Mybatis的mapper-locations配置問題
MyBatis 是一款優(yōu)秀的半自動的ORM持久層框架,它支持自定義 SQL、存儲過程以及高級映射。MyBatis 免除了幾乎所有的 JDBC 代碼以及設置參數(shù)和獲取結果集的工作,需要的朋友可以參考下2023-05-05
SpringBoot使用swagger生成api接口文檔的方法詳解
在之前的文章中,使用mybatis-plus生成了對應的包,在此基礎上,我們針對項目的api接口,添加swagger配置和注解,生成swagger接口文檔,需要的可以了解一下2022-10-10
spring+springmvc+mybatis 開發(fā)JAVA單體應用
這篇文章主要介紹了spring+springmvc+mybatis 開發(fā)JAVA單體應用的相關知識,本文通過圖文實例代碼的形式給大家介紹的非常詳細 ,需要的朋友可以參考下2018-11-11

