1.介绍mybatis-plus
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。 但是对于联表操作还必须使用mybatis
2.特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
- 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错 JDK1.
- 支持主键自动生成:支持多达 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
3.使用入门
- 创建一个springboot工程并加入相关的依赖
<!--①引入相关的依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
- 配置文件
# ②修改配置文件
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis-plus?serverTimezone=Asia/Shanghai
spring.datasource.password=root
spring.datasource.username=root
logging.level.com.ykq.mybatisplus.dao=debug
- 创建一个实体类
实体类属性对应mysql数据库表,自行创建
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
- 接口mapper
//③ 创建一个接口并继承BaseMapper
public interface UserMapper extends BaseMapper<User> {
}
- 在主启动类上mapper的扫描
package com.gsj.mybatisplus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.gsj.mybatisplus.mapper")
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
- 测试
①查询多条数据
@Resource
private UserMapper userMapper;
@Test
void contextLoads() {
List<User> userList = userMapper.selectList(null);
// Assert.assertEqualls(5,userList.size());
System.out.println(userList);
userList.forEach(System.out::println);
}
②指定id查询
@SpringBootTest
class MybatisPlusApplicationTests {
@Resource
private UserMapper userMapper;
@Test
void contextLoads() {
//根据id查询用户信息
User user = userMapper.selectById(1);
System.out.println(user);
}
}
需要在我们的实体类 id属性上加上注解 @TableI
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@TableId(type = IdType.AUTO)//递增 数据库里也得是递增
private Long id;
//列名和属性名不同
③ 删除 delete
- 逻辑删除
只对自动注入的sql起效:
插入: 不作限制
查找: 追加where条件过滤掉已删除数据,且使用 wrapper.entity 生成的where条件会忽略该字段
更新: 追加where条件防止更新到已删除数据,且使用 wrapper.entity 生成的where条件会忽略该字段
删除: 转变为
更新数据库 为逻辑删除加入逻辑字段deleted默认值为0
更新实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@TableId(type = IdType.AUTO)//递增 数据里也得是递增
private Long id;
//列名和属性名不同
@TableField(value = "uname")
private String name;
private Integer age;
private String email;
@TableLogic
private Integer deleted;
public User(Long id, String name, Integer age, String email, Integer deleted) {
this.id = id;
this.name = name;
this.age = age;
this.email = email;
this.deleted = deleted;
}
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
测试
@Test
public void testDelete(){
List<User> users = userMapper.selectList(null);
System.out.println(users);
int i = userMapper.deleteById(1);
System.out.println(i);
}
④修改
在数据库中加入
实体类
//新增执行
@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,"insertTime", Date.class,new Date());
this.strictInsertFill(metaObject,"updateTime",Date.class,new Date());
}
//修改执行这个方法
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject,"updateTime",Date.class,new Date());
}
}
测试
/**
* 自动填充:修改时会自动填充修改时间
* 添加时会自动填充添加时间和修改时间
*/
@Test
public void testUpdate(){
User user=new User(2L,"闫克起",49,"2300@qq.com",0);
int i = userMapper.updateById(user);
}
⑤ 查询—条件查询
/**
* 条件查询
*/
@Test
public void testSelectBycondication(){
// Wrapper: 条件的包装类。-QueryWrapper UpdateWrapper LambdaQueryWrapper LambdaUpdateWrapper
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",10,20);
wrapper.or();
wrapper.like("uname", "卜"); //模糊查询
// wrapper.orderByAsc("age"); //排序
//wrapper.select("count(*)");
// wrapper.groupBy("uname");
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:当前页码 每页显示的条数
*/
Page<User> page = new Page<>(1, 4);
Page<User> page1 = userMapper.selectPage(page, null);
System.out.println("当前的总页码"+page1.getPages());
System.out.println("总条数"+page1.getTotal());
System.out.println("当前页的记录"+page1.getRecords());
}