mybatisPlus简化开发过程
1.入门案例 1.1 SpringBoot整合Mybatis开发过程(复习)
2.Mp简介 3. 增删改查 4. 分页插件 5. 多条件查询(lambda版本) 6 条件查询的null值处理 7. Lambda查询投影 8.条件查询 8.1 范围查询(>、=、between) 8.2 模糊查询 (like) 8.3 空判定(null) 8.4 包含性判定(in) 8.5 分组(group) 8.6 排序(order)
9. 字段映射和表名映射不一致
10. id生成策略控制 10.1 不同的表应用不同的id生成策略 10.2 mp支持的id生成策略 10.3 配置id生成策略 10.4 全局指定id生成策略
11. 批量删除/查询 12.逻辑删除 12.1 逻辑删除全局配置 12.2 Mp中的逻辑删除说明
13.乐观锁 14. 代码生成器
1.入门案例
1.1 SpringBoot整合Mybatis开发过程(复习)
使用springInitialier创建springboot工程
new Module -> 填入属性
<?xml version="1.0" encoding="UTF-8"?>
< project xmlns = " http://maven.apache.org/POM/4.0.0" xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= " http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" >
< modelVersion> 4.0.0</ modelVersion>
< parent>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-starter-parent</ artifactId>
< version> 2.6.3</ version>
< relativePath/>
</ parent>
< groupId> com.ypy</ groupId>
< artifactId> mybatisplus_quickstart</ artifactId>
< version> 0.0.1-SNAPSHOT</ version>
< name> mybatisplus_quickstart</ name>
< description> mybatisplus_quickstart</ description>
< properties>
< java.version> 1.8</ java.version>
</ properties>
< dependencies>
< dependency>
< groupId> com.baomidou</ groupId>
< artifactId> mybatis-plus-boot-starter</ artifactId>
< version> 3.5.0</ version>
</ dependency>
< dependency>
< groupId> com.alibaba</ groupId>
< artifactId> druid</ artifactId>
< version> 1.2.16</ version>
</ dependency>
< dependency>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-starter</ artifactId>
</ dependency>
< dependency>
< groupId> mysql</ groupId>
< artifactId> mysql-connector-java</ artifactId>
< version> 8.0.23</ version>
< scope> runtime</ scope>
</ dependency>
< dependency>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-starter-test</ artifactId>
< scope> test</ scope>
</ dependency>
< dependency>
< groupId> org.projectlombok</ groupId>
< artifactId> lombok</ artifactId>
< version> 1.18.26</ version>
</ dependency>
</ dependencies>
< build>
< plugins>
< plugin>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-maven-plugin</ artifactId>
</ plugin>
</ plugins>
</ build>
</ project>
spring :
datasource :
type : com.alibaba.druid.pool.DruidDataSource
driver-class-name : com.mysql.cj.jdbc.Driver
url : jdbc: mysql: //localhost: 3306/mybatis? serverTimezone=UTC
username : root
password : root
mybatis-plus :
configuration :
log-impl : org.apache.ibatis.logging.stdout.StdOutImpl
import com. baomidou. mybatisplus. annotation. TableId ;
import com. baomidou. mybatisplus. annotation. TableName ;
import lombok. AllArgsConstructor ;
import lombok. Data ;
import lombok. NoArgsConstructor ;
import lombok. experimental. Accessors ;
@Accessors ( chain= true )
@AllArgsConstructor
@NoArgsConstructor
@Data
@TableName ( value = "tb_user" )
public class User {
@TableId ( "id" )
private Long id;
private String username;
private String password;
private String gender;
private String addr;
}
import com. baomidou. mybatisplus. core. mapper. BaseMapper ;
import com. ypy. mybatisplus_quickstart. model. User ;
import org. apache. ibatis. annotations. Mapper ;
@Mapper
public interface UserMapper extends BaseMapper < User > {
}
@SpringBootTest
class MybatisplusQuickstartApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void testGetAll ( ) {
QueryWrapper < User > wrapper = new QueryWrapper < > ( ) ;
wrapper. eq ( "gender" , "男" ) ;
List < User > users = userMapper. selectList ( wrapper) ;
System . out. println ( users) ;
}
}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.3)
2023-11-13 14:37:57.566 INFO 4740 --- [ main] .m.MybatisplusQuickstartApplicationTests : Starting MybatisplusQuickstartApplicationTests using Java 1.8.0_221 on DESKTOP-YPYJE7C with PID 4740 (started by ypykip in D:\Application\WorkSpace\self-learn\base-learn\mybatisplus_quickstart)
2023-11-13 14:37:57.566 INFO 4740 --- [ main] .m.MybatisplusQuickstartApplicationTests : No active profile set, falling back to default profiles: default
org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@4d33940d
_ _ |_ _ _|_. ___ _ | _
| | |\/|_)(_| | |_\ |_)||_|_\
/ |
3.5.0
2023-11-13 14:37:59.217 INFO 4740 --- [ main] .m.MybatisplusQuickstartApplicationTests : Started MybatisplusQuickstartApplicationTests in 1.909 seconds (JVM running for 2.778)
2023-11-13 14:37:59.567 INFO 4740 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
[User(id=9, username=小奥, password=456, gender=男, addr=北京)]
2023-11-13 14:38:00.669 INFO 4740 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closing ...
2023-11-13 14:38:00.671 INFO 4740 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closed
Process finished with exit code 0
2.Mp简介
MyBatisPlus概述
● MyBatisP1us(简称MP)是基于MyBatis框架基础上开发的增强型工具,旨在简化开发、提高效率
● 官网:https://mybatis.plus/ (网友送的) https://mp.baomidou.com/
3. 增删改查
@SpringBootTest
class MybatisplusQuickstartApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void testSave ( ) {
User user = new User ( ) ;
user. setId ( 2L ) . setUsername ( "tt" ) . setGender ( "女" ) . setAddr ( "天津" ) . setPassword ( "123456" ) ;
userMapper. insert ( user) ;
}
@Test
void testPage ( ) {
IPage < User > page = new Page < > ( 2 , 3 ) ;
userMapper. selectPage ( page, null ) ;
System . out. println ( "当前页码: " + page. getCurrent ( ) ) ;
System . out. println ( "每页显示数: " + page. getSize ( ) ) ;
System . out. println ( "一共多少页: " + page. getPages ( ) ) ;
System . out. println ( "一共多少条: " + page. getTotal ( ) ) ;
System . out. println ( "数据: " + page. getRecords ( ) ) ;
}
@Test
public void testGetAll ( ) {
QueryWrapper < User > wrapper = new QueryWrapper < > ( ) ;
wrapper. eq ( "gender" , "男" ) ;
List < User > users = userMapper. selectList ( wrapper) ;
System . out. println ( users) ;
}
}
4. 分页插件
@Component
public class MpInterceptor {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor ( ) {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor ( ) ;
mybatisPlusInterceptor. addInnerInterceptor ( new PaginationInnerInterceptor ( ) ) ;
return mybatisPlusInterceptor;
}
}
@Test
void testPage ( ) {
IPage < User > page = new Page < > ( 2 , 3 ) ;
userMapper. selectPage ( page, null ) ;
System . out. println ( "当前页码: " + page. getCurrent ( ) ) ;
System . out. println ( "每页显示数: " + page. getSize ( ) ) ;
System . out. println ( "一共多少页: " + page. getPages ( ) ) ;
System . out. println ( "一共多少条: " + page. getTotal ( ) ) ;
System . out. println ( "数据: " + page. getRecords ( ) ) ;
}
5. 多条件查询(lambda版本)
@Test
public void testGetAll ( ) {
LambdaQueryWrapper < User > qw = new LambdaQueryWrapper < > ( ) ;
qw. gt ( User :: getAge , 25 ) . lt ( User :: getAge , 30 ) ;
List < User > users = userMapper. selectList ( qw) ;
System . out. println ( users) ;
}
6 条件查询的null值处理
@Test
public void testUq ( ) {
UserQuery uq = new UserQuery ( ) ;
uq. setAge2 ( 30 ) ;
LambdaQueryWrapper < User > lqw = new LambdaQueryWrapper < > ( ) ;
lqw. lt ( uq. getAge2 ( ) != null , User :: getAge , uq. getAge2 ( ) ) ;
lqw. gt ( uq. getAge ( ) != null , User :: getAge , uq. getAge ( ) ) ;
List < User > users = userMapper. selectList ( lqw) ;
System . out. println ( users) ;
}
7. Lambda查询投影
@Test
public void testQs ( ) {
LambdaQueryWrapper < User > lqw = new LambdaQueryWrapper < > ( ) ;
lqw. select ( User :: getId , User :: getAge ) ;
List < User > userList = userMapper. selectList ( lqw) ;
System . out. println ( userList) ;
}
@Test
public void testSelectCount ( ) {
QueryWrapper < User > lqw = new QueryWrapper < > ( ) ;
lqw. select ( "count(*) as count, gender" ) ;
lqw. groupBy ( "gender" ) ;
List < Map < String , Object > > maps =
userMapper. selectMaps ( lqw) ;
System . out. println ( maps) ;
}
8.条件查询
8.1 范围查询(>、=、between)
8.2 模糊查询 (like)
8.3 空判定(null)
8.4 包含性判定(in)
8.5 分组(group)
8.6 排序(order)
@Test
public void testCondition ( ) {
LambdaQueryWrapper < User > lqw = new LambdaQueryWrapper < > ( ) ;
String username = "乐" ;
String password = "" ;
lqw. eq ( User :: getUsername , username) . eq ( User :: getPassword , password) ;
User users = userMapper. selectOne ( lqw) ;
System . out. println ( users) ;
LambdaQueryWrapper < User > wrapper = new LambdaQueryWrapper < > ( ) ;
wrapper. between ( User :: getAge , 25 , 30 ) ;
List < User > users1 = userMapper. selectList ( wrapper) ;
System . out. println ( users1) ;
LambdaQueryWrapper < User > queryWrapper = new LambdaQueryWrapper < > ( ) ;
queryWrapper. likeRight ( User :: getUsername , "周" ) ;
User user = userMapper. selectOne ( queryWrapper) ;
System . out. println ( user) ;
}
9. 字段映射和表名映射不一致
使用@TableField和@TableName
属性注解,位置:模型类属性定义上方,作用:设置当前属性对应的数据表的字段关系
范例:
@TableName("tb_user")
public class User {
@TableFiled(value ="pwd", select = false) // 告诉mp pwd 不参与查询
private String password;
@TableFiled(exist = false)
private Integer online; // 表示表里面不存在这个字段
}
10. id生成策略控制
10.1 不同的表应用不同的id生成策略
日志:自增(1,2,3,4,5,6) 购物订单:特殊规则(FQ235996299) 外卖单:关联地区日期等信息(10 04 20200314 34 91) 关系表:可省略id …
10.2 mp支持的id生成策略
package com. baomidou. mybatisplus. annotation ;
public enum IdType {
AUTO ( 0 ) ,
NONE ( 1 ) ,
INPUT ( 2 ) ,
ASSIGN_ID ( 3 ) ,
ASSIGN_UUID ( 4 ) ;
private final int key;
private IdType ( int key) {
this . key = key;
}
public int getKey ( ) {
return this . key;
}
}
10.3 配置id生成策略
如果想要使用数据库的自增策略,那么就可以使用type = IdType . AUTO ,
如果需要让程序员自己指定id,那么就可以在实体类上使用type = IdType . INPUT , 并且注意,将表上的id生成
策略去掉
如果使用雪花算法生成,则可以使用type= IdType . ASSIGN_ID , 这个会生成64 bit的数,也就是说数据库表的id
必须是64 位的int
如果想要使用uuid,可以使用type= IdType . ASSIGN_UUID .
使用auto策略的时候,数据库指定auto_increment即可,插入数据不用插入id 使用input策略的时候,数据库需要去掉自动策略,用户需要自己set id 使用雪花算法生成id,需要将实体的id设置为Long类型,并且数据库和表id字段没有策略,指定全局配置 使用uuid算法生成id,需要将实体类和表指定为string和Varchar类型
10.4 全局指定id生成策略
db-config :
id-type : assign_uuid
table-prefix : tb_
11. 批量删除/查询
@Test
public void testBatchSearchOrDelete ( ) {
Object [ ] ids = new Object [ ] { 8 , 2 } ;
userMapper. deleteBatchIds ( Arrays . asList ( ids) ) ;
List < User > users = userMapper. selectBatchIds ( Arrays . asList ( 1 , 10 , 9 ) ) ;
System . out. println ( users) ;
}
12.逻辑删除
@TableLogic ( value = "0" , delval = "1" )
private Integer deleted;
@Test
public void testDelete ( ) {
userMapper. deleteById ( 1 ) ;
}
12.1 逻辑删除全局配置
logic-delete-field : deleted
logic-not-delete-value : 0
logic-delete-value : 1
12.2 Mp中的逻辑删除说明
mp逻辑删除会将delete修改为update语句,并且在查询全部的时候,会加上条件 deleted = 0 ;
13.乐观锁
执行原理(依赖版本信息)
== > Preparing : UPDATE tb_user SET version= ? WHERE id= ? AND version= ? AND deleted= 0
== > Parameters : 2 ( Integer ) , 9 ( String ) , 1 ( Integer )
alter table tb_user add column version int default 1 ;
@Version
private Integer version;
mybatisPlusInterceptor. addInnerInterceptor ( new OptimisticLockerInnerInterceptor ( ) ) ;
@Test
void testOptimisticLock ( ) {
boolean flag = false ;
while ( ! flag) {
User user = userMapper. selectById ( "9" ) ;
user. setId ( "9" ) . setUsername ( "version修改" ) ;
int count = userMapper. updateById ( user) ;
if ( count == 1 )
flag = true ;
}
}
== > Preparing : SELECT id, username, password, gender, addr, age, deleted, version FROM tb_user WHERE id= ? AND deleted= 0
== > Parameters : 9 ( String )
<= = Columns : id, username, password, gender, addr, age, deleted, version
<= = Row : 9 , 小奥, 456 , 男, 北京, 36 , 0 , 2
<= = Total : 1
Closing non transactional SqlSession [ org. apache. ibatis. session. defaults. DefaultSqlSession@7397c6 ]
Creating a new SqlSession
SqlSession [ org. apache. ibatis. session. defaults. DefaultSqlSession@295bf2a ] was not registered for synchronization because synchronization is not active
JDBC Connection [ com. mysql. cj. jdbc. ConnectionImpl@36061cf3 ] will not be managed by Spring
== > Preparing : UPDATE tb_user SET username= ? , password= ? , gender= ? , addr= ? , age= ? , version= ? WHERE id= ? AND version= ? AND deleted= 0
== > Parameters : version修改( String ) , 456 ( String ) , 男( String ) , 北京( String ) , 36 ( Integer ) , 3 ( Integer ) , 9 ( String ) , 2 ( Integer )
<= = Updates : 1
14. 代码生成器
模版: MyBatisPlus提供 数据库配置:读取数据库获取信息 开发者自定义配置:手工配置 具体配置可以详见此链接