天天看点

MyBatisPlus的基本使用

概述

MyBatisPlus

是为了简化我们代码书写而诞生了,使用它之后我们可以减少大量SQL语句的书写,提升开发效率(就是让我们变得更懒),它内置了许多常用的SQL操作,我们在配置好之后就可以使用了。

使用

1. 建表

DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
-- 真实开发中,version(乐观锁)、deleted(逻辑删除)、gmt_create、gmt_modified
           

2.创建项目并引入依赖

  • 目录结构
    MyBatisPlus的基本使用
  • pom.xml
<!--   mp 依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
           
在引入了MyBatisPlus之后,就不需要引入MyBatis了,但是还要引入

mysql-connector-java

3.在启动类中添加包扫描

@SpringBootApplication
@MapperScan("com.example.mp.mapper") // 指定需要扫描的包
public class MpApplication {

    public static void main(String[] args) {
        SpringApplication.run(MpApplication.class, args);
    }

}

           

4.配置数据源

spring.datasource.username=root
spring.datasource.password=
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
           

5.创建与表对应的实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "user") // 指定表名
public class User {
    private Integer id;
    private String name;
    private Integer age;
    private String email;
}
           

6.创建Mapper

// 在对应的Mapper上面继承基本的类 BaseMapper
@Repository
public interface UserMapper extends BaseMapper<User> {
	// 所有的CRUD操作都已经编写完成了
	// 你不需要像以前的配置一大堆文件了!
}

           

7.测试

@SpringBootTest
class MybatisPlusApplicationTests {
	// 继承了BaseMapper,所有的方法都来自己父类
	// 我们也可以编写自己的扩展方法!
	@Autowired
	private UserMapper userMapper;
	@Test
	void contextLoads() {
	// 参数是一个 Wrapper ,条件构造器,这里我们先不用 null
	// 查询全部用户
	List<User> users = userMapper.selectList(null);
	users.forEach(System.out::println);
	}
}
           

8.安装插件

这里以安装分页为例子
  • 在配置类中配置
@Configuration
@EnableTransactionManagement

public class MybatisPlusConfig {
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}
           
  • 测试
分页查询除了使用

selectPage()

之外,还有其他操作,可以百度自行了解
@SpringBootTest
class MpApplicationTests {

    @Resource
    private UserMapper userMapper;
    @Test
    void contextLoads() {

        IPage<User> userPage = new Page<>(2, 2);//参数一是当前页,参数二是每页个数
         userPage = userMapper.selectPage(userPage, null);
         List<User> list = userPage.getRecords();
          for(User user : list){
              System.out.println(user);
         }
    }

}
           
本文只是介绍了MyBatisPlus最基本的使用,开发中用的知识还有好多:
  • 插入操作
  • 插入操作中主键的生成的不同策略
  • 更新操作
  • 自动填充(多用于创建时间和最近更新时间字段):https://mp.baomidou.com/guide/auto-fill-metainfo.html
  • 逻辑删除
  • 乐观锁
  • 条件构造器:https://www.jianshu.com/p/c5537559ae3a?utm_campaign=hugo
  • 分页查询