Spring Boot集成MyBatis實(shí)現(xiàn)通用Mapper的配置及使用
什么是通用Mapper
通用Mapper就是為了解決單表增刪改查,基于Mybatis的插件。開發(fā)人員不需要編寫SQL,不需要在DAO中增加方法,只要寫好實(shí)體類,就能支持相應(yīng)的增刪改查方法。
關(guān)于MyBatis,大部分人都很熟悉。MyBatis 是一款優(yōu)秀的持久層框架,它支持定制化 SQL、存儲(chǔ)過程以及高級(jí)映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動(dòng)設(shè)置參數(shù)以及獲取結(jié)果集。MyBatis 可以使用簡單的 XML 或注解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對(duì)象)映射成數(shù)據(jù)庫中的記錄。
不管是DDD(Domain Driven Design,領(lǐng)域驅(qū)動(dòng)建模)還是分層架構(gòu)的風(fēng)格,都會(huì)涉及到對(duì)數(shù)據(jù)庫持久層的操作,本文將會(huì)講解Spring Boot集成MyBatis如何實(shí)現(xiàn)通用Mapper。
Spring Boot集成MyBatis
引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> </dependency>
可以看到如上關(guān)于Mybatis引入了 mybatis-spring-boot-starter
,由Mybatis提供的starter。
數(shù)據(jù)庫配置
在application.yml中增加如下配置:
spring: datasource: hikari: connection-test-query: SELECT 1 minimum-idle: 1 maximum-pool-size: 5 pool-name: dbcp1 driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=utf-8 username: user password: pwd type: com.zaxxer.hikari.HikariDataSource schema[0]: classpath:/init.sql initialize: true
可以看到,我們配置了hikari和數(shù)據(jù)庫的基本信息。在應(yīng)用服務(wù)啟動(dòng)時(shí),會(huì)自動(dòng)初始化classpath下的sql腳本。
CREATE TABLE IF NOT EXISTS `test` ( `id` bigint(20) unsigned NOT NULL, `local_name` varchar(128) NOT NULL , PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
在sql腳本中,我們創(chuàng)建了一張 test 表。
到這里,后面我們一般需要配置Mybatis映射的xml文件和實(shí)體類的路徑。根據(jù)mybatis generator 自動(dòng)生成代碼。包括 XXMapper.java , XXEntity.java , XXMapper.xml 。這里我們就不演示了,直接進(jìn)入下一步的通用Mapper實(shí)現(xiàn)。
通用Mapper的使用
引入依賴
<dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.4.0</version> </dependency>
通用Mapper的作者 abel533 ,有興趣可閱讀源碼。
配置通用Mapper
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import tk.mybatis.spring.mapper.MapperScannerConfigurer; import java.util.Properties; @Configuration public class MyBatisMapperScannerConfig{ @Bean public MapperScannerConfigurer mapperScannerConfigurer(){ MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); mapperScannerConfigurer.setBasePackage("com.blueskykong.mybatis.dao");//掃描該路徑下的dao Properties properties = new Properties(); properties.setProperty("mappers", "com.blueskykong.mybatis.config.BaseDao");//通用dao properties.setProperty("notEmpty", "false"); properties.setProperty("IDENTITY", "MYSQL"); mapperScannerConfigurer.setProperties(properties); return mapperScannerConfigurer; } }
在配置中,設(shè)定了指定路徑下的dao,并指定了通用dao。需要注意的是, MapperScannerConfigurer 來自于 tk.mybatis.spring.mapper 包下。
BaseDao import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.common.MySqlMapper; public interface BaseDao<T>extends Mapper<T>,MySqlMapper<T>{ }
通用Mapper接口,其他接口繼承該接口即可。
創(chuàng)建實(shí)體
我們需要添加 test 表對(duì)應(yīng)的實(shí)體。
@Data @Table(name = "test") @AllArgsConstructor @NoArgsConstructor public class TestModel{ @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String localName; }
其中, @Table(name = "test")
注解指定了該實(shí)體對(duì)應(yīng)的數(shù)據(jù)庫表名。
配置文件
mybatis: configuration: map-underscore-to-camel-case: true
為了更好地映射Java實(shí)體和數(shù)據(jù)庫字段,我們指定下劃線駝峰法的映射配置。
TestDao編寫
public interface TestDaoextends BaseDao<TestModel>{ @Insert("insert into test(id, local_name) values(#{id}, #{localName})") IntegerinsertTestModel(TestModel testModel); }
TestDao 繼承自 BaseDao ,并指定了泛型為對(duì)應(yīng)的 TestModel 。 TestDao 包含繼承的方法,如:
int deleteByPrimaryKey(Integer userId); int insert(User record); int insertSelective(User record); UserselectByPrimaryKey(Integer userId); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record);
還可以自定義一些方法,我們在上面自定義了一個(gè) insertTestModel 方法。
Service層和控制層
本文略過這兩層,比較簡單,讀者可以參見本文對(duì)應(yīng)的源碼地址。
結(jié)果驗(yàn)證
我們在插入一條數(shù)據(jù)之后,查詢對(duì)應(yīng)的實(shí)體。對(duì)應(yīng)執(zhí)行的結(jié)果也都是成功,可以看到控制臺(tái)的如下日志信息:
c.b.mybatis.dao.TestDao.insertTestModel : ==> Preparing: insert into test(id, local_name) values(?, ?)
c.b.mybatis.dao.TestDao.insertTestModel : ==> Parameters: 5953(Integer), testName(String)
c.b.mybatis.dao.TestDao.insertTestModel : <== Updates: 1
c.b.m.dao.TestDao.selectByPrimaryKey : ==> Preparing: SELECT id,local_name FROM test WHERE id = ?
c.b.m.dao.TestDao.selectByPrimaryKey : ==> Parameters: 5953(Integer)
c.b.m.dao.TestDao.selectByPrimaryKey : <== Total: 1
Spring Boot集成MyBatis實(shí)現(xiàn)通用Mapper到此就大功告成。
小結(jié)
MyBatis是持久層非常常用的組件,Spring Boot倡導(dǎo)約定優(yōu)于配置,特別是很多xml的配置。當(dāng)然還有很多同學(xué)使用Spring Data。相比而言,我覺得MyBatis的SQL比Spring Data更加靈活,至于具體比較不在此討論。
本文對(duì)應(yīng)的源碼地址:
https://github.com/keets2012/Spring-Boot-Samples/tree/master/mybatis-demo
總結(jié)
以上所述是小編給大家介紹的Spring Boot集成MyBatis實(shí)現(xiàn)通用Mapper的配置及使用,希望對(duì)大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
Java利用HttpClient模擬POST表單操作應(yīng)用及注意事項(xiàng)
本文主要介紹JAVA中利用HttpClient模擬POST表單操作,希望對(duì)大家有所幫助。2016-04-04關(guān)于Spring的@Transaction導(dǎo)致數(shù)據(jù)庫回滾全部生效問題(又刪庫跑路)
使用@Transactional一鍵開啟聲明式事務(wù), 這就真的事務(wù)生效了?過于信任框架總有“意外驚喜”。本文通過案例給大家詳解關(guān)于Spring的@Transaction導(dǎo)致數(shù)據(jù)庫回滾全部生效問題,感興趣的朋友一起看看吧2021-05-05@PathVariable注解,讓spring支持參數(shù)帶值功能的案例
這篇文章主要介紹了@PathVariable注解,讓spring支持參數(shù)帶值功能的案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-02-02使用Spring Boot實(shí)現(xiàn)操作數(shù)據(jù)庫的接口的過程
本文給大家分享使用Spring Boot實(shí)現(xiàn)操作數(shù)據(jù)庫的接口的過程,包括springboot原理解析及實(shí)例代碼詳解,感興趣的朋友跟隨小編一起看看吧2021-07-07Mac OS X 下 IntelliJ IDEA、jEdit 等 Java 程序中文標(biāo)點(diǎn)輸入無效的完美解決方法
Mac OS X 下基于 Java 的程序會(huì)出現(xiàn)中文標(biāo)點(diǎn)輸入無效的問題,在中文輸入法狀態(tài),可以輸入中文字,但輸入中文標(biāo)點(diǎn)最后上去的是英文標(biāo)點(diǎn).這篇文章主要介紹了Mac OS X 下 IntelliJ IDEA、jEdit 等 Java 程序中文標(biāo)點(diǎn)輸入無效的完美解決方法,需要的朋友可以參考下2016-10-10巧用FutureTask 線程池輕松解決接口超時(shí)問題
這篇文章主要為大家介紹了使用FutureTask結(jié)合線程池輕松解決接口超時(shí)問題的巧妙用法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11spring?boot集成WebSocket日志實(shí)時(shí)輸出到web頁面
這篇文章主要為大家介紹了spring?boot集成WebSocket日志實(shí)時(shí)輸出到web頁面展示的詳細(xì)操作,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03