MyBatis-Ext快速入門實(shí)戰(zhàn)
最近在工作中,接觸到了一個MyBatis擴(kuò)展工具包MyBatis-Ext,可以說很大程度上減輕了使用mybatis時的工作量,本文就和大家來分享一下這個輕量的擴(kuò)展工具。
MyBatis-Ext是MyBatis的增強(qiáng)擴(kuò)展,和我們平常用的Mybatis-plus非常類似,簡化了MyBatis對單表增刪改查的操作,提供通用的增刪改查,支持函數(shù)式編程,支持分頁查詢,支持用戶自定義通用方法,并且能夠防止SQL注入。集成起來也非常簡單,對MyBatis只做增強(qiáng)不做修改。
以spring-boot項(xiàng)目為例,集成非常簡單。pom導(dǎo)入核心依賴:
<dependency>
<groupId>tech.wetech.mybatis</groupId>
<artifactId>mybatis-ext-core</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>tech.wetech.mybatis</groupId>
<artifactId>mybatis-ext-spring-boot-starter</artifactId>
<version>1.5.2</version>
</dependency>
需要注意的是,引入mybatis-ext-spring-boot-starter后無需再引入mybatis-spring-boot-starter。
和以往一樣,在application.yml配置一下數(shù)據(jù)源:
spring:
datasource:
username: dater
password: 123456
url: jdbc:mysql://127.0.0.1:3306/datacenter?useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 8
min-idle: 1
max-active: 20
mybatis:
mapper-locations: classpath:mapping/*Mapper.xml
type-aliases-package: com.mybatis.ext.test.mybatisexttest.entity
spring:
datasource:
username: dater
password: 123456
url: jdbc:mysql://127.0.0.1:3306/datacenter?useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 8
min-idle: 1
max-active: 20
mybatis:
mapper-locations: classpath:mapping/*Mapper.xml
type-aliases-package: com.mybatis.ext.test.mybatisexttest.entity
創(chuàng)建一個映射的實(shí)體類:
@Data
@Table(name = "user")
public class User {
@Id
String identifycard;
@Column(name="name")
String name;
String money;
String card;
String phone;
String rate;
}
mybatis-ext使用了Jpa的注解,目前實(shí)現(xiàn)了@Table、@Id、@Column、@Transient、@Version。其中@Table、@Id是必須添加的注解,其他非必須添加。使用@Table指定數(shù)據(jù)表名,@Id指定數(shù)據(jù)表主鍵。
查詢的Mapper接口繼承BaseMapper接口,泛型中填寫實(shí)體類:
public interface UserMapper extends BaseMapper<User> {
}
我們來看一下能夠直接調(diào)用的方法,為在BaseMapper中內(nèi)置了很多通用方法,可以直接調(diào)用,非常簡便:
int deleteByPrimaryKey(PK id);
<S extends T> int insert(S record);
<S extends T> int insertAll(Iterable<S> record);
<S extends T> int insertSelective(S record);
<S extends T> S selectByPrimaryKey(PK id);
<S extends T> Optional<S> selectByPrimaryKeyWithOptional(ID id);
<S extends T> int updateByPrimaryKey(S record);
<S extends T> int updateByPrimaryKeySelective(S record);
<S extends T> List<S> selectAll();
<S extends T> List<S> selectList(S record);
<S extends T> S selectOne(S record);
<S extends T> S selectOneWithOptional(S record);
boolean existsByPrimaryKey(PK id);
<S extends T> int count(S record);
<S extends T> List<S> selectByExample(Example<S, Object> example);
<S extends T> int countByExample(Example<S, Object> example);
<S extends T> int deleteByExample(Example<S, Object> example);
<S extends T> int updateByExample(@Param("record") S record, @Param("example") Example<S, Object> example);
<S extends T> int updateByExampleSelective(@Param("record") S record, @Param("example") Example<S, Object> example);
來進(jìn)行一下接口調(diào)用的測試,先試一下selectAll方法:
@GetMapping("getUser")
public void getUser(){
List<User> users = userMapper.selectAll();
for (User user : users) {
System.out.println(user.getName()+" "+user.getIdentifycard());
}
}
測試結(jié)果:

這樣,通過調(diào)用內(nèi)置方法就實(shí)現(xiàn)了不寫sql語句直接進(jìn)行查詢。同樣,如果想根據(jù)主鍵進(jìn)行查詢也很簡單,直接調(diào)用selectByPrimaryKey方法:
@PostMapping("getUserById")
public void getUserByIdentifycard(@RequestBody User user){
User retUser = userMapper.selectByPrimaryKey(user);
System.out.println(retUser.toString());
}
查詢結(jié)果:

另外,還可以使用Optional包裹查詢,修改一下上面主鍵查詢的方法:
@PostMapping("getUserById")
public void getUserByIdentifycard(@RequestBody User user){
User retUser = userMapper.selectByPrimaryKeyWithOptional(user)
.orElseThrow(()->new RuntimeException("未查到數(shù)據(jù)"));
System.out.println(retUser.toString());
}
這樣,在傳入一個不存在的主鍵時,就會直接拋出自定義的異常:
還有其他很多簡單的查詢,大家可以根據(jù)上面列出api自行測試一下。此外,還可以使用Criteria,使用邏輯組合,進(jìn)行函數(shù)式查詢:
@GetMapping("criteriaTest")
public void testCreateCriteria(){
List<User> list = userMapper.createCriteria()
.andEqualTo(User::getName, "Trunks")
.andBetween(User::getMoney, 100, 300)
.andNotLike(User::getRate, "6")
.orIn(User::getCard, Arrays.asList("10"))
.selectList();
list.forEach(user -> {
System.out.println(user.toString());
});
}
查詢結(jié)果:

也可以使用Example進(jìn)行查詢:
@GetMapping("exampleTest")
public void testExample(){
Example<User> example=Example.of(User.class);
example.createCriteria()
.andEqualTo(User::getName, "Trunks")
.andBetween(User::getMoney, 100, 300)
.andNotLike(User::getRate, "6")
.orIn(User::getCard, Arrays.asList("10"));
example.setDistinct(true);
List<User> list = userMapper.selectByExample(example);
list.forEach(user -> {
System.out.println(user.toString());
});
}
結(jié)果與使用Criteria結(jié)果相同。另外,還可以將多個條件組合使用:
GetMapping("testExampleWithSub")
public void selectByExampleWithSub(){
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper userMapper1 = session.getMapper(UserMapper.class);
Example<User> example=Example.of(User.class);
example.and()
.andEqualTo(User::getName, "Trunks");
example.and()
.andEqualTo(User::getCard,"10");
example.and()
.andLessThanOrEqualTo(User::getRate,300);
Criteria<User> criteria=new Criteria<>();
criteria.andIsNotNull(User::getPhone);
example.and(criteria);
List<User> list = userMapper1.selectByExample(example);
list.forEach(user -> {
System.out.println(user.toString());
});
}
}
結(jié)果:

除了上面介紹的這些功能與基礎(chǔ)的sql增刪改查外,MyBatis-Ext還實(shí)現(xiàn)了很多其他功能,例如排序和分頁,并且支持自定義通用接口方法等等,大家可以在使用中通過實(shí)踐繼續(xù)探索一下。
最后
到此這篇關(guān)于MyBatis-Ext快速入門實(shí)戰(zhàn)的文章就介紹到這了,更多相關(guān)MyBatis-Ext 入門內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用maven整合Spring+SpringMVC+Mybatis框架詳細(xì)步驟(圖文)
這篇文章主要介紹了使用maven整合Spring+SpringMVC+Mybatis框架詳細(xì)步驟(圖文),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05
SpringMVC+Mysql實(shí)例詳解(附demo)
本篇文章主要介紹了SpringMVC+Mysql實(shí)例詳解(附demo),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。2016-12-12
超細(xì)致講解Spring框架 JdbcTemplate的使用
在之前的Javaweb學(xué)習(xí)中,學(xué)習(xí)了手動封裝JdbcTemplate,其好處是通過(sql語句+參數(shù))模板化了編程。而真正的JdbcTemplate類,是Spring框架為我們寫好的。它是 Spring 框架中提供的一個對象,是對原始 Jdbc API 對象的簡單封裝。2021-09-09
Java JSON轉(zhuǎn)成List結(jié)構(gòu)數(shù)據(jù)
這篇文章主要介紹了Java JSON轉(zhuǎn)成List結(jié)構(gòu)數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
JDK8 new ReentrantLock((true)加鎖流程
這篇文章主要介紹了java面試中常遇到的問題JDK8 new ReentrantLock((true)加鎖流程示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
Java生成訂單號或唯一id的高并發(fā)方案(4種方法)
本文主要介紹了Java生成訂單號或唯一id的高并發(fā)方案,包括4種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-01-01

