1.特性(官网可查)
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
官网https://mp.baomidou.com/guide/quick-start.html#%E6%B7%BB%E5%8A%A0%E4%BE%9D%E8%B5%96
#简介
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。。
特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
- 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
- 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
- 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
- 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
- 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
- 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
- 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
2.使用
首先引入所需依赖
//引入 Spring Boot Starter 父工程:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version>
<relativePath/>
</parent>
//引入 spring-boot-starter、spring-boot-starter-test、mybatis-plus-boot-starter、h2 依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>Latest Version</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
配置文件
# ②修改配置文件
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/库名?serverTimezone=Asia/Shanghai
spring.datasource.password=root
spring.datasource.username=root
logging.level.com.ykq.mybatisplus.dao=debug
创建接口
public interface TabUser extends BaseMapper<User> {
}
主启动项找到dao层
@SpringBootApplication
@MapperScan(basePackages = {"dao层路径"})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
进行增删改查,创建实体类,例如:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
查询,以测试类为例
可直接调用select相关函数
//查询所有
void select(){
List<User> list=tabUser.selectList(null);
System.out.println(list);
}
条件查询(官网可查)
@Test
public void testSelectByCondication(){
// Wrapper: 条件的包装类。-QueryWrapper UpdateWrapper LambdaQueryWrapper LambdaUpdateWrapper
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.between("age",12,18);
wrapper.or();
wrapper.like("u_name","刘");
wrapper.orderByDesc("age");
// wrapper.select("count(*)");
// wrapper.groupBy("u_name");
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
分页查询(官网可查)
配置类需要引入如下配置
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
测试
@Test
public void testSelectByPage(){
Page<User> page=new Page<>(3,4);
Page<User> page1 = userMapper.selectPage(page, null);
System.out.println("当前的总页码:"+page1.getPages());
System.out.println("总条数:"+page1.getTotal());
System.out.println("当前页的记录:"+page1.getRecords());
}
添加insert:
例:id为主键按照数据库自增,name属性名与数据库字段名不一致时,实体类需要写如下注解
public class User {
@TableId(type = IdType.AUTO) //必须数据库也是递增
private Long id;
//如果列名和属性名不同
@TableField(value = "u_name")
private String name;
private Integer age;
private String email;
}
测试:
void insert(){
User user=new User(null,"zs",12,"aa@qq.com");//new一个实体对象放入insert函数内
int i=tabUser.insert(user);
System.out.println(i);
}
删除delete:
可以根据id直接调用deletById函数删除,例
@GetMapping("/user/{id}")
public String delete(@PathVariable("id") Integer id) {
tabUser.deleteById(id);
return "redirect:/main";
}
逻辑删除需要创建一个新的字段,类型为int,0代表存在,1代表删除
实体类里边新添加的字段上要加@TableLogic注解
测试
@Test
public void testDelete(){
int i = userMapper.deleteById(2);
System.out.println(i);
}
其实就是把值为0的修改为1,数据库里边数据并没有被删除。查询默认只查寻值为0的数据。前台起到了删除的作用。
修改update:
可直接调用updateById函数,
@GetMapping("/user")
//获得一个实体,根据实体对原数据进行修改
public String update(User user) {
tabUser.updateById(user);
return "redirect:/main";
}
自动填充(官网可查)
添加添加时间,修改时间字段,并写上如下注解
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
创建一个配置类
@Configuration
public class MybatisPlusConfig implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
/**
* 为哪个字段做自动填充
*/
this.strictInsertFill(metaObject, "createTime", Date.class, new Date()); // 起始版本 3.3.0(推荐使用)
this.strictInsertFill(metaObject, "updateTime", Date.class, new Date()); // 起始版本 3.3.0(推荐使用)
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date()); // 起始版本 3.3.0(推荐)
}
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
当进行添加,修改时,系统会自动填充当前时间、