Mybatis-plus
介绍
国产的开源框架,基于myBatis,核心就是简化mybatis开发,提高效率。
依赖
com.baomidou
mybatis-plus
3.5.1
基本使用
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private int age;
private String work;
}
springboot配置文件
# 数据源
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybean?serverTimezone=UTC
username: root
password: makangming
# 打印日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
启动类
//mapper扫描
@SpringBootApplication
@MapperScan("com.example.demo.dao")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
测试类
// !不要写sql /??
@SpringBootTest
@SuppressWarnings("all")
class DemoApplicationTests {
@Autowired
UserMapper mapper;
@Test
void contextLoads() {
mapper.selectList(null).forEach(System.out::println);
}
}
常用注解
@TableName
介绍
映射数据表名。用在类上。
@TableField
介绍
映射普通字段,用在属性上。
exist
boolean值,是否为数据库映射字段。
select
是否查询该字段值。
fill
表示是否自动填充(有mybatis plus自动给字段赋值)。
FieldFill枚举用来声明填充的时机(需要创建一个处理器来生成填充值):
DEFAULT → 不填充
INSERT → 添加记录时填充
UPDATE → 更新时填充
INSERT_UPDATE → 添加和更新时都添加
定义处理器
@Component
public class UserMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("实体类的属性名称","填充的值",metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("实体类的属性名称","填充的值,Object类型",metaObject);
}
}
@TableId
介绍
映射关系主键。用在属性上。
value
对应表字段。
type
对应字段的主键类型。
AUTO → 自增
NONE → MP set 主键(自动生成主键),雪花算法实现(注意:类型类型需要设置成long,太短了存不下)
INPUT → 需要开发者手动赋值
ASSIGN_ID → MP分配ID,Long、Integer、String
ASSIGN_UUID → 分配UUID,String
@Version
介绍
标记乐观锁(想要乐观锁生效需要注册一个配置类)。
配置类
@Configuration
public class myBatisPlusConfig {
//返回一个乐观锁的拦截器
@Bean
public OptimisticLockerInnerInterceptor getOptimisticLockerInnerInterceptor(){
return new OptimisticLockerInnerInterceptor();
}
}
@EnumValue
介绍
通用的枚举类注解,将数据库字段映射成实体类的枚举类型。
枚举
public enum StatusEnum {
WORK(1,"上班"),
REST(0,"休息");
StatusEnum(int code,String msg){
this.code = code;
this.msg = msg;
}
@EnumValue
private int code;
private String msg;
}
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@TableField
private int id;
private String name;
private int age;
private String work;
private StatusEnum code;
}
@TableLogic
介绍
映射逻辑删除,表示这条数据已经不需要使用了,但是不能在数据库中删除。比如 销号,账号已经没了,但是实际上并没有在数据库中删除,只是已经没有人使用了。通常在数据中额外定义一条字段,用来表示这条记录是否还在使用。给对应的实体类属性加上这一条注解即可。
springboot配置
# 数据源
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybean?serverTimezone=UTC
username: root
password: makangming
# 打印日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
# 0表示还在使用,1表示已经被删除
logic-delete-field: 1
logic-not-delete-value: 0
CRUD
增
不加条件的全部查询
mapper.selectList(null);
有条件的查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("name","张三");
wrapper.in("age",1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19);
wrapper.orderByAsc("age");
mapper.selectList(wrapper).forEach(System.out::println);
//gt是小于等于
//ge是大于等于
//ne是不等于
//表示id in 子查询的结果
wrapper.inSql("id","select id from user where id>10");
......
分页
增加配置
@Configuration
public class myBatisPlusConfig {
//返回一个乐观锁的拦截器
@Bean
public OptimisticLockerInnerInterceptor getOptimisticLockerInnerInterceptor(){
return new OptimisticLockerInnerInterceptor();
}
//分页处理器
@Bean
public MybatisPlusInterceptor getPaginationInnerInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return mybatisPlusInterceptor;
}
}
测试
@SpringBootTest
@SuppressWarnings("all")
class DemoApplicationTests {
@Autowired
UserMapper mapper;
@Test
void contextLoads() {
//创建分页规则(第二页,每页两个)
Page page = new Page<>(2,2);
//查询
Page userPage = mapper.selectPage(page,null);
//获取结果
userPage.getRecords().forEach(System.out::println);
}
}
自定义SQL
mapper定义sql
public interface UserMapper extends BaseMapper {
@Select("select name,age,work from user where id=#{id}")
public Map getUserAttrById(int id);
}
测试
@SpringBootTest
@SuppressWarnings("all")
class DemoApplicationTests {
@Autowired
UserMapper mapper;
@Test
void contextLoads() {
Map userAttrById = mapper.getUserAttrById(12);
for (String key : userAttrById.keySet()) {
System.out.println(key+" → "+userAttrById.get(key).toString());
}
}
}
自动生成
介绍
根据数据表自动生成实体类、mapper、service、serviceImpl、Controller。
依赖
com.baomidou
mybatis-plus-generator
3.3.1.tmp
org.apache.velocity
velocity
1.7
事务
自定义的配置类
@Configuration
@EnableTransactionManagement //开启事务管理 -- 实测这一步可以不要
public class MyBatisPlusConfig {
//分页处理器
@Bean
public MybatisPlusInterceptor getInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return mybatisPlusInterceptor;
}
}
使用事务
@Service
@Transactional //为下面的每个方法都开启一个事务
public class UserService {
@Autowired
UserMapper userMapper;
public int delUser(int id){
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("id",id);
return userMapper.delete(wrapper);
}
public int delUser(String username,String password){
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("username",username);
wrapper.eq("password",password);
return userMapper.delete(wrapper);
}
public int updUser(int id,User data){
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("id",id);
return userMapper.update(data, wrapper);
}
public int addUser(User user){
return userMapper.insert(user);
}
//用来测试
public void test(){
System.out.println("---------------------------------↓");
delUser(16);
int i = 1 / 0;
System.out.println(loginUser("张三丰", "111"));
System.out.println("-----------------------------------↑");
}
}