SpringBoot+Mybatis使用Mapper接口注冊(cè)的幾種方式
SpringBoot項(xiàng)目中借助Mybatis來(lái)操作數(shù)據(jù)庫(kù),對(duì)大部分java技術(shù)棧的小伙伴來(lái)說(shuō),并不會(huì)陌生;我們知道,使用mybatis,一般會(huì)有下面幾個(gè)
- Entity: 數(shù)據(jù)庫(kù)實(shí)體類
- Mapper: db操作接口
- Service: 服務(wù)類
- xml文件:寫sql的地方
本篇博文中主要介紹是Mapper接口與對(duì)應(yīng)的xml文件如何關(guān)聯(lián)的幾種姿勢(shì)(這個(gè)問(wèn)題像不像"茴"字有幾個(gè)寫法😬)
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 '用戶名', `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)建時(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)行開發(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. 實(shí)例演示
前面基礎(chǔ)環(huán)境搭建完成,接下來(lái)準(zhǔn)備下Mybatis的Entity,Mapper等基礎(chǔ)類
1. 實(shí)體類,Mapper類
數(shù)據(jù)庫(kù)實(shí)體類MoneyPo
@Data public class MoneyPo { private Integer id; private String name; private Long money; private Integer isDeleted; private Timestamp createAt; private Timestamp updateAt; }
對(duì)應(yīng)的Mapper接口(這里直接使用注解的方式來(lái)實(shí)現(xiàn)CURD)
public interface MoneyMapper { /** * 保存數(shù)據(jù),并保存主鍵id * * @param po * @return int */ @Options(useGeneratedKeys = true, keyProperty = "po.id", keyColumn = "id") @Insert("insert into money (name, money, is_deleted) values (#{po.name}, #{po.money}, #{po.isDeleted})") int save(@Param("po") MoneyPo po); /** * 更新 * * @param id id * @param money 錢 * @return int */ @Update("update money set `money`=#{money} where id = #{id}") int update(@Param("id") int id, @Param("money") long money); /** * 刪除數(shù)據(jù) * * @param id id * @return int */ @Delete("delete from money where id = #{id}") int delete(@Param("id") int id); /** * 主鍵查詢 * * @param id id * @return {@link MoneyPo} */ @Select("select * from money where id = #{id}") @Results(id = "moneyResultMap", value = { @Result(property = "id", column = "id", id = true, jdbcType = JdbcType.INTEGER), @Result(property = "name", column = "name", jdbcType = JdbcType.VARCHAR), @Result(property = "money", column = "money", jdbcType = JdbcType.INTEGER), @Result(property = "isDeleted", column = "is_deleted", jdbcType = JdbcType.TINYINT), @Result(property = "createAt", column = "create_at", jdbcType = JdbcType.TIMESTAMP), @Result(property = "updateAt", column = "update_at", jdbcType = JdbcType.TIMESTAMP)}) MoneyPo getById(@Param("id") int id); }
對(duì)應(yīng)的Service類
@Slf4j @Service public class MoneyService { @Autowired private MoneyMapper moneyMapper; public void basicTest() { int id = save(); log.info("save {}", getById(id)); boolean update = update(id, 202L); log.info("update {}, {}", update, getById(id)); boolean delete = delete(id); log.info("delete {}, {}", delete, getById(id)); } private int save() { MoneyPo po = new MoneyPo(); po.setName("一灰灰blog"); po.setMoney(101L); po.setIsDeleted(0); moneyMapper.save(po); return po.getId(); } private boolean update(int id, long newMoney) { int ans = moneyMapper.update(id, newMoney); return ans > 0; } private boolean delete(int id) { return moneyMapper.delete(id) > 0; } private MoneyPo getById(int id) { return moneyMapper.getById(id); } }
2. 注冊(cè)方式
注意,上面寫完之后,若不通過(guò)下面的幾種方式注冊(cè)Mapper接口,項(xiàng)目啟動(dòng)會(huì)失敗,提示找不到MoneyMapper對(duì)應(yīng)的bean
Field moneyMapper in com.git.hui.boot.mybatis.service.MoneyService required a bean of type 'com.git.hui.boot.mybatis.mapper.MoneyMapper' that could not be found.
2.1 @MapperScan注冊(cè)方式
在配置類or啟動(dòng)類上,添加@MapperScan注解來(lái)指定Mapper接口的包路徑,從而實(shí)現(xiàn)Mapper接口的注冊(cè)
@MapperScan(basePackages = "com.git.hui.boot.mybatis.mapper") @SpringBootApplication public class Application { public Application(MoneyService moneyService) { moneyService.basicTest(); } public static void main(String[] args) { SpringApplication.run(Application.class); } }
執(zhí)行之后輸出結(jié)果如下
2021-07-06 19:12:57.984 INFO 1876 --- [ main] c.g.h.boot.mybatis.service.MoneyService : save MoneyPo(id=557, name=一灰灰blog, money=101, isDeleted=0, createAt=2021-07-06 19:12:57.0, updateAt=2021-07-06 19:12:57.0)
2021-07-06 19:12:58.011 INFO 1876 --- [ main] c.g.h.boot.mybatis.service.MoneyService : update true, MoneyPo(id=557, name=一灰灰blog, money=202, isDeleted=0, createAt=2021-07-06 19:12:57.0, updateAt=2021-07-06 19:12:57.0)
2021-07-06 19:12:58.039 INFO 1876 --- [ main] c.g.h.boot.mybatis.service.MoneyService : delete true, null
注意:
- basePackages: 傳入Mapper的包路徑,數(shù)組,可以傳入多個(gè)
- 包路徑支持正則,如com.git.hui.boot.*.mapper
- 上面這種方式,可以避免讓我們所有的mapper都放在一個(gè)包路徑下,從而導(dǎo)致閱讀不友好
- 上面這種方式,可以避免讓我們所有的mapper都放在一個(gè)包路徑下,從而導(dǎo)致閱讀不友好
2.2 @Mapper 注冊(cè)方式
前面的@MapperScan指定mapper的包路徑,這個(gè)注解則直接放在Mapper接口上
@Mapper public interface MoneyMapper { ... }
測(cè)試輸出省略...
2.3 MapperScannerConfigurer注冊(cè)方式
使用MapperScannerConfigurer來(lái)實(shí)現(xiàn)mapper接口注冊(cè),在很久以前,還是使用Spring的xml進(jìn)行bean的聲明的時(shí)候,mybatis的mapper就是這么玩的
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="xxx"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean>
對(duì)應(yīng)的java代碼如下:
@Configuration public class AutoConfig { @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")); return bean.getObject(); } @Bean("sqlSessionTemplate") public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory storySqlSessionFactory) { return new SqlSessionTemplate(storySqlSessionFactory); } @Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setBasePackage("com.git.hui.boot.mybatis.mapper"); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); mapperScannerConfigurer.setSqlSessionTemplateBeanName("sqlSessionTemplate"); return mapperScannerConfigurer; } }
測(cè)試輸出省略
3. 小結(jié)
本文主要介紹Mybatis中Mapper接口的三種注冊(cè)方式,其中常見的兩種注解方式
- @MapperScan: 指定Mapper接口的包路徑
- @Mapper: 放在mapper接口上
- MapperScannerConfigurer: 編程方式注冊(cè)
那么疑問(wèn)來(lái)了,為啥要介紹這三種方式,我們實(shí)際的業(yè)務(wù)開發(fā)中,前面兩個(gè)基本上就滿足了;什么場(chǎng)景會(huì)用到第三種方式?
如寫通用的Mapper(類似Mybatis-Plus中的BaseMapper)
如一個(gè)Mapper,多數(shù)據(jù)源的場(chǎng)景(如主從庫(kù),冷熱庫(kù),db的操作mapper一致,但是底層的數(shù)據(jù)源不同)
III. 不能錯(cuò)過(guò)的源碼和相關(guān)知識(shí)點(diǎn)
工程:https://github.com/liuyueyi/spring-boot-demo
源碼:https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/104-mybatis-ano
到此這篇關(guān)于SpringBoot+Mybatis使用Mapper接口注冊(cè)的幾種方式的文章就介紹到這了,更多相關(guān)SpringBoot Mapper接口注冊(cè)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Servlet+MyBatis項(xiàng)目轉(zhuǎn)Spring Cloud微服務(wù),多數(shù)據(jù)源配置修改建議
- MyBatis實(shí)現(xiàn)注冊(cè)及獲取Mapper
- SpringBoot+Mybatis實(shí)現(xiàn)登錄注冊(cè)的示例代碼
- IDEA下創(chuàng)建SpringBoot+MyBatis+MySql項(xiàng)目實(shí)現(xiàn)動(dòng)態(tài)登錄與注冊(cè)功能
- Spring boot+mybatis+thymeleaf 實(shí)現(xiàn)登錄注冊(cè)增刪改查功能的示例代碼
- Spring MVC+mybatis實(shí)現(xiàn)注冊(cè)登錄功能
- Mybatis與微服務(wù)注冊(cè)的詳細(xì)過(guò)程
相關(guān)文章
Java concurrency之鎖_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要為大家詳細(xì)介紹了Java concurrency之鎖的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06macOS中搭建Java8開發(fā)環(huán)境(基于Intel?x86?64-bit)
這篇文章主要介紹了macOS中搭建Java8開發(fā)環(huán)境(基于Intel?x86?64-bit)?的相關(guān)資料,需要的朋友可以參考下2022-12-12零基礎(chǔ)如何系統(tǒng)的學(xué)習(xí)Java
這篇文章主要介紹了零基礎(chǔ)如何系統(tǒng)的學(xué)習(xí)Java,很多朋友糾結(jié)這個(gè)問(wèn)題,教材書不知道從何學(xué)起,今天小編給大家分享一篇教程幫助到家梳理這方面的知識(shí)2020-07-07SpringCloud基于Feign的可編程式接口調(diào)用實(shí)現(xiàn)
本文主要介紹了SpringCloud基于Feign的可編程式接口調(diào)用實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04解決IDEA和CMD中java命令提示錯(cuò)誤: 找不到或無(wú)法加載主類的問(wèn)題
這篇文章主要介紹了解決IDEA和CMD中java命令提示錯(cuò)誤: 找不到或無(wú)法加載主類的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09idea中無(wú)法自動(dòng)裝配未找到 ‘XXXXXXX‘ 類型的 Bean
本文主要介紹了idea中無(wú)法自動(dòng)裝配未找到 ‘XXXXXXX‘ 類型的 Bean的原因及三種解決方法,具有一定的參考價(jià)值,感興趣的可以了解一下2024-03-03