mybatis-plus
新建工程
< dependency>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-starter</ artifactId>
</ dependency>
< dependency>
< groupId> mysql</ groupId>
< artifactId> mysql-connector-java</ artifactId>
< scope> runtime</ scope>
</ dependency>
< dependency>
< groupId> com.baomidou</ groupId>
< artifactId> mybatis-plus-boot-starter</ artifactId>
< version> 3.5.1</ version>
</ dependency>
< dependency>
< groupId> org.projectlombok</ groupId>
< artifactId> lombok</ artifactId>
< optional> true</ optional>
</ dependency>
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/xxx?characterEncoding=utf-8&userSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=xxxx
spring.datasource.password=xxxx
# 加入日志配置
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 设置mybatis-plus全局配置
# 设置表前缀
mybatis-plus.global-config.db-config.table-prefx=t_
# 设置统一主键生成策略
mybatis-plus.global-config.id-type=auto
# 设置类型别名
mybatis-plus.type-aliases-package=xxx.xxx.pojo
@SpringBootApplication
@MapperScan ( "xxx.xxx.mapper" )
public class Application {
public static void main ( String [ ] agrs) {
SpringApplication . run ( Application . class , args) ;
}
}
@Data
@TableName ( "t_user" )
public class User {
@TabledId
private Long id;
private String name;
private Integer age;
private String email;
}
xxx.xxx.mapper.UserMapper
@Repository
public interface UserMapper extends BaseMapper < User > {
}
@Autowired
private UserMapper userMapper;
public void testSelectList ( ) {
List < User > list = userMapper. selectList ( null ) ;
list. forEach ( System . out:: println ) ;
}
BaseMapper
insert(T entity) deleteById() deleteByMap(Map<String,Object> map) deleteBatchIds(Collection<?> ids) updateById(T entity) selectById() selectBatchIds(Collection<?> ids) selectByMap(Map<String,Object> map) selectList(Wrapper wrapper)
条件构造器
Wrapper:条件构造器
AbstractWrapper
QueryWrapper:查询条件封装 UpdateWrapper:update条件封装 AbstractLambdaWrapper
LambdaQueryWrapper LambdaUpdateWrapper
QueryWrapper
QueryWrapper < User > queryWrapper = new QueryWrapper < > ( ) ;
queryWrapper. like ( "user_name" , "a" )
. between ( "age" , 20 , 30 )
. isNotNull ( "email" )
. orderByDesc ( "age" )
. orderByAsc ( "id" ) ;
userMapper. selectList ( queryWrapper) ;
根据条件delete
QueryWrapper < User > queryWrapper = new QueryWrapper < > ( ) ;
queryWrapper. isNull ( "email" ) ;
userMapper. delete ( queryWrapper) ;
根据条件update
QueryWrapper < User > queryWrapper = new QueryWrapper < > ( ) ;
queryWrapper. gt ( "age" , 20 )
. like ( "user_name" , "a" )
. or ( )
. isNull ( "email" ) ;
User user = new User ( ) ;
user. setName ( "xxx" ) ;
user. setEmail ( "xxx@xxx.com" ) ;
userMapper. update ( user, queryWrapper) ;
查询优先级
QueryWrapper < User > queryWrapper = new QueryWrapper < > ( ) ;
queryWrapper. like ( "user_name" , "a" )
. and ( i-> i. gt ( "age" , 20 )
. or ( )
. isNull ( "email" )
) ;
User user = new User ( ) ;
user. setName ( "xxx" ) ;
user. setEmail ( "xxx@xxx.com" ) ;
userMapper. update ( user, queryWrapper) ;
组装查询field
QueryWrapper < User > queryWrapper = new QueryWrapper < > ( ) ;
queryWrapper. select ( "user_name" , "age" , "email" ) ;
userMapper. selectMaps ( queryWrapper) ;
组装子查询
QueryWrapper < User > queryWrapper = new QueryWrapper < > ( ) ;
queryWrapper. inSql ( "uid" , "select uid from t_user where uid<=1000" ) ;
List < User > list = userMapper. selectList ( queryWrapper) ;
condition组装
String username = "" ;
Integer ageBegin = null ;
Integer ageEnd = 30 ;
QueryWrapper queryWrapper = new QueryWrapper ( ) ;
queryWrapper. like ( StringUtils . isNotBlank ( username) , "user_name" , username)
. ge ( ageBegin!= null , "age" , ageBegin)
. le ( ageEnd!= null , "age" , ageEnd) ;
List < User > list = userMapper. selectList ( queryWrapper) ;
UpadteyWrapper
UpdateWrapper < User > updateWrapper = new UpdateWrapper < > ( ) ;
updateWrapper. like ( "user_name" , "a" )
. and ( i-> i. gt ( "age" , 20 ) . or ( ) . isNull ( "email" ) ) ;
updateWrapper. set ( "user_name" , "xxx" )
. set ( "email" , "xxx" ) ;
userMapper. update ( null , updateWrapper) ;
LambdaQueryWrapper
String username = "" ;
Integer ageBegin = null ;
Integer ageEnd = 30 ;
LambdaQueryWrapper queryWapper = new LambdaQueryWrapper ( ) ;
queryWrapper. like ( StringUtils . isNotBlank ( username) , User :: getName , username)
. ge ( ageBegin!= null , User :: getAge , ageBegin)
. le ( ageEnd!= null , , User :: getAge , ageEnd) ;
List < User > list = userMapper. selectList ( queryWrapper) ;
LambdaUpdateWrapper
String username = "" ;
Integer ageBegin = null ;
Integer ageEnd = 30 ;
LambdaUpdateWrapper updateWapper = new LambdaUpdateWrapper ( ) ;
updateWapper. like ( User :: getName , "a" )
. and ( i-> i. gt ( User :: getAge , 20 ) . or ( ) . isNull ( User :: getEmail ) ) ;
updateWrapper. set ( User :: getName , "xxx" )
. set ( User :: getEmail , "xxx" ) ;
userMapper. update ( null , updateWrapper) ;
自定义功能
xxx.xxx.mapper.UserMapper
@Repository
public interface UserMapper extends BaseMapper < User > {
Map < String , Object > selectMapById ( Long id) ;
}
resources/mapper/UserMapper.xml
<? xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE mapper
PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
< mapper namespace = " xxx.xxx.mapper.UserMapper" >
< select id = " selectMapById" resultType = " Map" >
select id,name,age,email from user where id=#{id}
</ select>
</ mapper>
通用Servie接口
xxx.xxx.service.UserService
saveBatch(Collection list)
public interface UserService extends IService < User > {
}
xxx.xxx.service.impl.UserServiceImpl
@Service
public class UserServiceImpl extends ServiceImpl < UserMapper , User > implements UserService {
}
test
@Autowired
private UserService userService;
public void test ( ) {
long count = userService. count ( ) ;
}
注解
@TableName(“user”)
@TableId(value=“”,type=IdType.AUTO)
将属性对应的字段指定为主键 value
type
主键生成策略 IdType.AUTO:自增 IdType.ASSIGN_ID:默认,雪花算法 @TableField @TableLogic
分页
@Configuration
@MapperScan ( "xxx.xxx.mapper" )
public class MyBatisPlusConfig {
@Bean
public MyBatisPlusInterceptor MybatisPlusInterceptor ( ) {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor ( ) ;
interceptor. addInnerInterceptor ( new PaginationInterceptor ( DbType . MYSQL) ) ;
return interceptor;
}
}
int current = 1 ;
int size = 3 ;
Page < User > page = new Page ( current, size) ;
userMapper. selectPage ( page, null )
Page
page.getRecords()
page.getCurrent() page.getSize() page.getPages()
page.getTotal() page.hasNext()
page.hasPrevious()
自定义方法的分页
xxx.xxx.mapper.UserMapper
@Repository
public interface UserMapper extends BaseMapper < User > {
Page < User > selectPageVo ( @Param ( "page" ) Page < User > page, @Param ( "age" ) Integer age) ;
}
resources/mapper/UserMapper.xml
<? xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE mapper
PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
< mapper namespace = " xxx.xxx.mapper.UserMapper" >
< select id = " selectPageVo" resultType = " xxx.xxx.pojo.User" >
select * from user where age>#{age}
</ select>
</ mapper>
乐观锁
@Configuration
@MapperScan ( "xxx.xxx.mapper" )
public class MyBatisPlusConfig {
@Bean
public MyBatisPlusInterceptor MybatisPlusInterceptor ( ) {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor ( ) ;
interceptor. addInnerInterceptor ( new PaginationInterceptor ( DbType . MYSQL) ) ;
interceptor. addInnerInterceptor ( new OptimisticLockerInnerInterceptor ( ) ) ;
return interceptor;
}
}
@Version
private Integer version;
通用枚举
# 扫描枚举所在包
mybatis-plus.type-enums-package=xxx.xxx.enums
@Getter
public enum SexEnum {
MALE ( 1 , "男" ) ,
FEMALE ( 2 , "女" ) ;
@EnumValue
private Integer sex;
private String sexName;
SexEnum ( Integer sex, String sexName) {
this . sex = sex;
this . sexName = sexName;
}
}
private SexEnum sex;
代码生成器
< dependency>
< groupId> com.baomidou</ groupId>
< artifactId> mybatis-plus-generator</ artifactId>
< version> 3.5.1</ version>
</ dependency>
< dependency>
< groupId> org.freemarker</ groupId>
< artifactId> freemarker</ artifactId>
< version> 2.3.31</ version>
</ dependency>
public static void main ( String [ ] args) {
FastAutoGenerator . create ( "url" , "username" , "password" )
. globalConfig ( builder -> {
builder. author ( "xxx" )
. fileOverride ( )
. outputDir ( "/data" ) ;
} )
. packageConfig ( builder -> {
builder. parent ( "xxx.xxx" )
. moduleName ( "xxx" )
. pathInfo ( Collections . singletonMap ( OutputFile . mapperXml, "/data/mapper" ) ) ;
} )
. strategyConfig ( builder -> {
builder. addInclude ( "t_user" )
. addTablePrefix ( "t_" , "c_" ) ;
} )
. templateEngine ( new FreemarkerTemplateEngine ( ) )
. execute ( ) ;
}
多数据源
< dependency>
< groupId> com.baomidou</ groupId>
< artifactId> dynamic-datasource-spring-boot-starter</ artifactId>
< version> 3.5.0</ version>
</ dependency>
# 默认数据源
spring.datasource.dynamic.primary=master
# 是否严格模式
spring.datasource.dynamic.strict=false
spring.datasource.dynamic.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.master.url=jdbc:mysql://localhost:3306/xxx?characterEncoding=utf-8&userSSL=false
spring.datasource.dynamic.datasource.master.username=xxxx
spring.datasource.dynamic.datasource.master.password=xxxx
spring.datasource.dynamic.datasource.slave_1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.slave_1.url=jdbc:mysql://localhost:3306/xxx?characterEncoding=utf-8&userSSL=false
spring.datasource.dynamic.datasource.slave_1.username=xxxx
spring.datasource.dynamic.datasource.slave_1.password=xxxx
xxx.xxx.service.UserService
public interface UserService extends IService < User > {
}
xxx.xxx-service.impl.UserServiceImpl
@Service
@DS ( "master" )
public class UserServiceImpl extends ServiceImpl < UserMapper , User > implemnts UserService {
}
@MapperScan ( "xxx.xxx.mapper" )
插件