mybatis plus笔记_梳碧湖的砍柴人.exe的博客-爱代码爱编程
Mybatis plus笔记
文章目录
前言
Mybatis plus学习笔记
一、Mybatis plus介绍
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。Mybatis plus官网
二、创建Spring Boot工程
1.工程依赖 pom.xml
<!-- mybatis plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2.数据源配置 Application.yml
server:
port: 8081
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 88888888
url: jdbc:mysql://localhost:3306/cargo_managment?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
此配置是用于打印sql语句的,mybatis plus默认不打印sql语句
3.mysql student表
create table student(
id int(8) primary key ,
name varchar(10) ,
age int(3)
);
4.创建Student实体类
package com.example.mybayisplus.entity;
import lombok.Data;
/**
* @author 权哥
* @version 1.0
* @date 2022/9/18 14:43
*/
@Data
public class Student {
private long id;
private String name;
private long age;
}
5.创建Mapper接口
package com.example.mybayisplus.Mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.mybayisplus.entity.Student;
/**
* @author 权哥
* @version 1.0
* @date 2022/9/18 14:47
*/
public interface StudentMapper extends BaseMapper<Student> {
}
6. 测试
package com.example.mybayisplus;
import com.example.mybayisplus.Mapper.StudentMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MybayisplusApplicationTests {
@Autowired
private StudentMapper studentMapper;
@Test
void contextLoads() {
studentMapper.selectList(null).forEach(System.out::println);
}
}
7.结果
三、Mybayis plus常用注解
1.@TableName
@Data
@TableName(value = "student")
public class Class {
private long id;
private String name;
private long age;
}
当实体类的名字与数据库的名字不一致时,通过@TableName注解来映射数据库的表名。(Mybatis plus 默认以实体类名称首字母小写与数据库表名进行映射)
2.@TableId
设置主键映射,value映射主键字段名,type设置主键类型,主键的生成策略
例:
@Data
public class Student {
@TableId(type = IdType.NONE)
private long id;
private String student_name;
private long age;
}
值 | 描述 |
---|---|
AUTO | 数据库自增 |
NONE | MP set 主键。雪花算法实现 |
INPUT | 需要开发者手动赋值 |
ASSIFN_ID | MP 分配ID、Long、Integer、String |
ASSIGN_UUID | 分配UUID,String |
3.@TableField
(1)@TableField(value = “name”)
@Data
public class Student {
private long id;
@TableField(value = "name")
private String student_name;
private long age;
}
当数据库表中属性名称与实体类属性名称不一致时,可以通过@TableField注解来完成实体类属性与数据库属性的映射,同时要注意数据类型、长度等是否匹配。
(2)@TableField(exist = false)
@Data
public class Student {
private long id;
private String name;
private long age;
@TableField(exist = false)
private int a;
}
exist表示是否为数据库字段,如果实体类中的成员变量在数据库中没有对应的字段,则可使用exist=false
(3) @TableField(select = false)
@Data
public class Student {
private long id;
private String name;
@TableField(select = false)
private long age;
}
select表示是否查询该字段
(4) @TableField(fill = FieldFill.INSERT)& @TableField(fill = FieldFill.INSERT_UPDATE)
@Data
public class Student {
private long id;
private String name;
private long age;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
@TableField(fill = FieldFill.INSERT)
表示第一次插入数据时,插入createTime数据,在后期对数据进行更新时,createTime属性的数据不进行改变,保留第一次插入的数据
@TableField(fill = FieldFill.INSERT_UPDATE)
表示第一次插入数据时,插入updateTime数据 ,但是在后期对数据进行更新时,只修改updateTime属性的数据
注意,此方式需要创建一个自动填充的处理器,并且需要将此方法注入到Spring IoC容器
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
MetaObjectHandler为mybatis plus提供
文件路径
4.@Version
标记乐观锁,通过version字段来保证数据的安全性,当修改数据的时候,会以version作为条件,当条件成立的时候才会修改成功
(1)往数据库添加version字段,默认值为1
(2)实体类添加version属性并添加啊@Version注解
@Data
public class Student {
private long id;
private String name;
private long age;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Version
private Integer version;
}
(3)注册MybatisPLus config配置类
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor optimisticLockerInnerInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor=new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mybatisPlusInterceptor;
}
}
(4)测试
@Autowired
private StudentMapper studentMapper;
@Test
void update(){
Student student=studentMapper.selectById(1);
student.setName("张伟1");
Student student2=studentMapper.selectById(1);
student2.setName("张伟2");
studentMapper.updateById(student2);
studentMapper.updateById(student);
}
5.实现枚举的两种方式
(1)使用@EnumValue注解
创建枚举类:
public enum StatusEnum {
上班(1, "上班"),
休息(0,"休息");
StatusEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
@EnumValue
private Integer code;
private String msg;
}
实体类添加status属性
@Data
public class Student {
private long id;
private String name;
private AgeEnum age;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Version
private Integer version;
private StatusEnum status;
}
数据库添加status字段,默认值为1
测试
通过注解的方式是将被@EnumValue注解的属性与数据库的字段进行映射
(2)通过接口实现
public enum AgeEnum implements IEnum<Integer> {
one(1,"一岁"),
two(2,"两岁"),
three(3,"三岁");
AgeEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
private Integer code;
private String msg;
@Override
public Integer getValue() {
return this.code;
}
}
实体类修改age属性类型为AgeEnum
@Data
public class Student {
private long id;
private String name;
private AgeEnum age;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Version
private Integer version;
private StatusEnum status;
}
结果
6. @TableLogic映射逻辑删除
数据库添加deleted字段,默认值为0,0为不删除,1为删除
实体类添加deleted属性
@Data
public class Student {
private long id;
private String name;
private long age;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@Version
@TableField(fill = FieldFill.DEFAULT )
private Integer version;
@TableField(fill = FieldFill.DEFAULT )
private StatusEnum status;
@TableLogic
private Integer deleted;
}
Application.yml配置
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
logic-not-delete-value: 0
logic-delete-value: 1