天天看點

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
  • 分頁查詢