Spring Boot集成MyBatis實(shí)現(xiàn)通用Mapper的配置及使用
什么是通用Mapper
通用Mapper就是為了解決單表增刪改查,基于Mybatis的插件。開(kāi)發(fā)人員不需要編寫(xiě)SQL,不需要在DAO中增加方法,只要寫(xiě)好實(shí)體類(lèi),就能支持相應(yīng)的增刪改查方法。
關(guān)于MyBatis,大部分人都很熟悉。MyBatis 是一款優(yōu)秀的持久層框架,它支持定制化 SQL、存儲(chǔ)過(guò)程以及高級(jí)映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動(dòng)設(shè)置參數(shù)以及獲取結(jié)果集。MyBatis 可以使用簡(jiǎn)單的 XML 或注解來(lái)配置和映射原生信息,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對(duì)象)映射成數(shù)據(jù)庫(kù)中的記錄。
不管是DDD(Domain Driven Design,領(lǐng)域驅(qū)動(dòng)建模)還是分層架構(gòu)的風(fēng)格,都會(huì)涉及到對(duì)數(shù)據(jù)庫(kù)持久層的操作,本文將會(huì)講解Spring Boot集成MyBatis如何實(shí)現(xiàn)通用Mapper。
Spring Boot集成MyBatis
引入依賴(lài)
<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ù)庫(kù)配置
在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ù)庫(kù)的基本信息。在應(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í)體類(lèi)的路徑。根據(jù)mybatis generator 自動(dòng)生成代碼。包括 XXMapper.java , XXEntity.java , XXMapper.xml 。這里我們就不演示了,直接進(jìn)入下一步的通用Mapper實(shí)現(xiàn)。
通用Mapper的使用
引入依賴(lài)
<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 來(lái)自于 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ù)庫(kù)表名。
配置文件
mybatis: configuration: map-underscore-to-camel-case: true
為了更好地映射Java實(shí)體和數(shù)據(jù)庫(kù)字段,我們指定下劃線(xiàn)駝峰法的映射配置。
TestDao編寫(xiě)
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);
還可以自定義一些方法,我們?cè)谏厦孀远x了一個(gè) insertTestModel 方法。
Service層和控制層
本文略過(guò)這兩層,比較簡(jiǎn)單,讀者可以參見(jiàn)本文對(duì)應(yīng)的源碼地址。
結(jié)果驗(yàn)證
我們?cè)诓迦胍粭l數(shù)據(jù)之后,查詢(xún)對(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。相比而言,我覺(jué)得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ì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
解決@ResponseBody作用在返回類(lèi)型為String的方法時(shí)的坑
這篇文章主要介紹了解決@ResponseBody作用在返回類(lèi)型為String的方法時(shí)的坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
Spring Cloud超詳細(xì)i講解Feign自定義配置與使用
這篇文章主要介紹了SpringCloud Feign自定義配置與使用,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
如何使用spring-ws發(fā)布webservice服務(wù)
文章介紹了如何使用Spring-WS發(fā)布Web服務(wù),包括添加依賴(lài)、創(chuàng)建XSD文件、生成JAXB實(shí)體、配置Endpoint、啟動(dòng)服務(wù)等步驟,結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-11-11
IDEA報(bào)錯(cuò)Error?running‘Application‘:Command?line?is?too?lo
這篇文章主要介紹了IDEA報(bào)錯(cuò)Error?running?‘Application‘:Command?line?is?too?long的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06

