SpringBoot+Mybatis實(shí)現(xiàn)Mapper接口與Sql綁定幾種姿勢(shì)
通常我們?cè)谑褂肕ybatis進(jìn)行開(kāi)發(fā)時(shí),會(huì)選擇xml文件來(lái)寫(xiě)對(duì)應(yīng)的sql,然后將Mapper接口與sql的xml文件建立綁定關(guān)系,然后在項(xiàng)目中調(diào)用mapper接口就可以執(zhí)行對(duì)應(yīng)的sql
那么如何將Mapper接口與sql進(jìn)行綁定呢?本文將介紹四種常見(jiàn)的姿勢(shì)
- 默認(rèn)策略
- SpringBoot配置參數(shù)mybatis.mapper-locations
- <mapper>指定
- SqlSessionFactory指定
I. 環(huán)境準(zhǔn)備
1. 數(shù)據(jù)庫(kù)準(zhǔn)備
使用mysql作為本文的實(shí)例數(shù)據(jù)庫(kù),新增一張表
CREATE TABLE `money` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL DEFAULT '' COMMENT '用戶(hù)名', `money` int(26) NOT NULL DEFAULT '0' COMMENT '錢(qián)', `is_deleted` tinyint(1) NOT NULL DEFAULT '0', `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時(shí)間', `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時(shí)間', PRIMARY KEY (`id`), KEY `name` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
2. 項(xiàng)目環(huán)境
本文借助 SpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEA進(jìn)行開(kāi)發(fā)
pom依賴(lài)如下
<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. 實(shí)例演示
環(huán)境搭建完畢,準(zhǔn)備對(duì)應(yīng)的實(shí)體類(lèi),Mapper接口
1. 實(shí)體類(lèi),Mapper接口
數(shù)據(jù)庫(kù)實(shí)體類(lèi): 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; }
一個(gè)基礎(chǔ)的Mapper接口
@Mapper public interface MoneyMapper { trueint savePo(@Param("po") MoneyPo po); }
一個(gè)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文件
寫(xiě)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綁定
以上為代碼層面實(shí)現(xiàn)CURD的基礎(chǔ)知識(shí),基本上就是mybatis操作的那些套路,沒(méi)有什么需要特殊注意的;接下來(lái)我們進(jìn)入本文主題
如何告訴mybatis,將上面的MoenyMapper接口與xml文件關(guān)聯(lián)起來(lái)
3.1 默認(rèn)方式
采用默認(rèn)的綁定方式,不需要我們做額外的操作,重點(diǎn)是需要遵循規(guī)則
- xml的目錄結(jié)構(gòu),與Mapper接口的包路徑完全一致
- xml文件名與Mapper接口名完全一致(注意大小寫(xiě)都要完全一致)
請(qǐng)注意上面的另個(gè)完全一致
使用默認(rèn)的方式進(jìn)行綁定時(shí),一個(gè)示例如上圖;特別需要注意的是文件名的大小寫(xiě),xml文件的目錄層級(jí)都需要完全一致
如果使用上面這種方式,在執(zhí)行時(shí),依然提示有問(wèn)題,排查的思路就是查看 target目錄下生成的class文件與xml文件是否在一起,如下圖就是正常的case
再次說(shuō)明
基于上面的case,我們可以直接將xml文件,與mapper接口寫(xiě)在一起,不放在資源路徑resources下面
3.2 SpringBoot配置
SpringBoot提供了一個(gè)簡(jiǎn)單的配置,來(lái)指定Mapper接口與sql的綁定,一行配置即可
mybatis: mapper-locations: classpath:sqlmapper/*.xml
使用這種方式就比較簡(jiǎn)單了,不要求xml文件與Mapper接口文件名一致;也沒(méi)有指定路徑層級(jí)一致
3.3 Mapper標(biāo)簽
mapper標(biāo)簽,需要放在mybatis的配置文件中,因此我們首先通過(guò)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>
通過(guò)上面的mapper標(biāo)簽來(lái)指定注冊(cè)關(guān)系,也是可行的,詳情可參考官方文檔 !
https://mybatis.org/mybatis-3/configuration.html#mappers
3.4 SqlSessionFactory
在前面一篇介紹Mapper接口注冊(cè)的博文中,就介紹了通過(guò)qlSessionFactory+ MapperScannerConfigurer來(lái)注冊(cè)
這里也是可以通過(guò)SqlSessionFactory來(lái)指定xml文件的
@Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations( // 設(shè)置mybatis的xml所在位置,這里使用mybatis注解方式,沒(méi)有配置xml文件 new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/*.xml")); // 注冊(cè)typehandler,供全局使用 bean.setTypeHandlers(new Timestamp2LongHandler()); bean.setPlugins(new SqlStatInterceptor()); return bean.getObject(); }
4. 小結(jié)
本文主要介紹了四種Mapper接口與sql文件關(guān)系綁定的姿勢(shì),了解幾種不同的姿勢(shì)的特點(diǎn),在實(shí)際的項(xiàng)目開(kāi)發(fā)中,選擇一個(gè)即可
- 默認(rèn):在resource資源目錄下,xml文件的目錄層級(jí)與Mapper接口的包層級(jí)完全一致,且xml文件名與mapper接口文件名也完全一致
- 如mapper接口: com.git.hui.boot.mybatis.mapper.MoneyMapper
- 對(duì)應(yīng)的xml文件: com/git/hui/boot/mybatis/mapper/MoneyMapper.xml
- springboot配置參數(shù):
- application.yml配置文件中,指定 mybatis.mapper-locations=classpath:sqlmapper/*.xml
- mybatis-config配置文件
- 這種姿勢(shì)常見(jiàn)于非SpringBoot項(xiàng)目集成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注解方式,沒(méi)有配置xml文件 bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/*.xml"));
除了上面幾種方式之外,mybatis還支持無(wú)xml的方式,完全依靠注解來(lái)實(shí)現(xiàn)sql的拼裝,因此也就不存在映射關(guān)系綁定了,關(guān)于注解的case,可以參考博文【DB系列】Mybatis+注解整合篇
III. 不能錯(cuò)過(guò)的源碼和相關(guān)知識(shí)點(diǎn)
項(xiàng)目
工程: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實(shí)現(xiàn)Mapper接口與Sql綁定幾種姿勢(shì)的文章就介紹到這了,更多相關(guān)SpringBoot Mybatis Mapper接口與Sql綁定內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談關(guān)于Mybatis的mapper-locations配置問(wèn)題
MyBatis 是一款優(yōu)秀的半自動(dòng)的ORM持久層框架,它支持自定義 SQL、存儲(chǔ)過(guò)程以及高級(jí)映射。MyBatis 免除了幾乎所有的 JDBC 代碼以及設(shè)置參數(shù)和獲取結(jié)果集的工作,需要的朋友可以參考下2023-05-05Java實(shí)現(xiàn)選擇排序算法的實(shí)例教程
這篇文章主要介紹了Java實(shí)現(xiàn)選擇排序算法的實(shí)例教程,選擇排序的時(shí)間復(fù)雜度為О(n²),需要的朋友可以參考下2016-05-05SpringBoot使用swagger生成api接口文檔的方法詳解
在之前的文章中,使用mybatis-plus生成了對(duì)應(yīng)的包,在此基礎(chǔ)上,我們針對(duì)項(xiàng)目的api接口,添加swagger配置和注解,生成swagger接口文檔,需要的可以了解一下2022-10-10spring+springmvc+mybatis 開(kāi)發(fā)JAVA單體應(yīng)用
這篇文章主要介紹了spring+springmvc+mybatis 開(kāi)發(fā)JAVA單體應(yīng)用的相關(guān)知識(shí),本文通過(guò)圖文實(shí)例代碼的形式給大家介紹的非常詳細(xì) ,需要的朋友可以參考下2018-11-11java如何對(duì)map進(jìn)行排序詳解(map集合的使用)
這篇文章主要介紹了java如何對(duì)map進(jìn)行排序,java map集合的使用詳解,大家可以參考使用2013-12-12