官网地址:https://mp.baomidou.com/
一、基本使用
1、引入依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
2、实体类注解
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private int age;
private String email;
}
3、编写操作实体类的 Mapper 类
package mapper;
import bean.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface UserMapper extends BaseMapper<User> {
}
4、启动类加入扫描Mapper类
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("mapper")
@SpringBootApplication
public class TestMybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(TestMybatisPlusApplication.class, args);
}
}
5、测试类测试
import bean.User;
import mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class TestMybatisPlusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
for(User user:userList) {
System.out.println(user);
}
}
}
二、常用注解
2.1【@TableName 】
@TableName 用于定义表名
注:
常用属性:
value 用于定义表名
2.2【@TableId】
@TableId 用于定义表的主键
注:
常用属性:
value 用于定义主键字段名
type 用于定义主键类型(主键策略 IdType)
主键策略:
IdType.AUTO 主键自增,系统分配,不需要手动输入【数据库中该字段要设置为自动递增】
IdType.NONE 未设置主键
IdType.INPUT 需要自己输入 主键值。
IdType.ASSIGN_ID 系统分配 ID,用于数值型数据(Long,对应 mysql 中 BIGINT 类型)。
IdType.ASSIGN_UUID 系统分配 UUID,用于字符串型数据(String,对应 mysql 中 varchar(32) 类型)。
2.3【@TableField】
@TableField 用于定义表的非主键字段。
注:
常用属性:
value 用于定义非主键字段名
exist 用于指明是否为数据表的字段, true 表示是,false 为不是。表示当前属性不是数据库的字段,但在项目中必须使用
fill 用于指定字段填充策略(FieldFill)。
字段填充策略:(一般用于填充 创建时间、修改时间等字段)
FieldFill.DEFAULT 默认不填充
FieldFill.INSERT 插入时填充
FieldFill.UPDATE 更新时填充
FieldFill.INSERT_UPDATE 插入、更新时填充。
自动填充生效有三点:1.字段上加注解 2.新建一个类,实现MetaObjectHandler接口 3.将实现的bean配置到spring容器中。
2.4【@TableLogic】
@TableLogic 用于定义表的字段进行逻辑删除(非物理删除)【调用BaseMapper的deleteById(id)或者调用IService的removeById(id)时会使用】
注:
常用属性:
value 用于定义未删除时字段的值
delval 用于定义删除时字段的值
注意: 高于3.1.1版本的不需要再配置逻辑删除组件,低版本没有配置逻辑删除的bean会不生效,建议使用高版本的,比如3.3.1版。
2.5【@Version】
@Version 用于字段实现乐观锁
三、application.yml配置
mybatis-plus:
#Mapper中有自定义方法(XML 中有自定义实现)f需指定
mapper-locations: classpath*:/mapper/**/*.xml
#MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名
type-aliases-package: com.jgs.*.entity
configuration:
#sql日志打印
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
#启动时关闭mybatis-plus的banner
banner: false
db-config:
#逻辑删除规则统一配置
logic-delete-value: 1
logic-not-delete-value: 0
#主键类型AUTO:"数据库ID自增"
id-type: AUTO
四、QueryWrapper查询使用