Spring Boot 2 (十一):如何優雅的使用 MyBatis 之 MyBatis-Plus

MyBatis-Plus 是 MyBatis 的第三方使用插件。

前兩天在公衆號中發了《Spring Boot(六):如何優雅的使用 Mybatis》,有朋友留言說能不能寫一下整合 MyBatis-Plus 的教程。

在這之前我對 MyBatis-Plus 其實瞭解不是很多,一般情況下也不太願意使用第三方的組件。找時間瞭解了一下 MyBatis-Plus 發現還是國人出品的開源項目,並且在 Github 上有 5000 多個關注,說明在國內使用的用戶已經不少。

這篇文章就給大家介紹一下,如何在 Spring Boot 中整合 MyBatis-Plus 使用 MyBatis。

MyBatis-Plus 介紹

MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,爲簡化開發、提高效率而生。

官方願景:成爲 MyBatis 最好的搭檔,就像 魂鬥羅 中的 1P、2P,基友搭配,效率翻倍。

根據願景甚至還設置了一個很酷的 Logo。

官網地址:https://mybatis.plus/,本文大部分內容參考自官網。

特性

官網說的特性太多了,挑了幾個有特點的分享給大家。

  • 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
  • 損耗小:啓動即會自動注入基本 CURD,性能基本無損耗,直接面向對象操作
  • 強大的 CRUD 操作:內置通用 Mapper、通用 Service,僅僅通過少量配置即可實現單表大部分 CRUD 操作,更有強大的條件構造器,滿足各類使用需求
  • 支持 Lambda 形式調用:通過 Lambda 表達式,方便的編寫各類查詢條件,無需再擔心字段寫錯
  • 支持多種數據庫:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、SQLServer 等多種數據庫
  • 內置分頁插件:基於 MyBatis 物理分頁,開發者無需關心具體操作,配置好插件之後,寫分頁等同於普通 List 查詢

快速上手

準備數據

我們首先設計一個這樣的用戶表,如下:

id name age email
1 neo 18 [email protected]
2 keep 36 [email protected]
3 pure 28 [email protected]
4 smile 21 [email protected]
5 it 24 [email protected]

我們要創建兩個 Sql 文件,以便項目啓動的時候,將表結構和數據初始化到數據庫。

表結構文件(schema-h2.sql)內容:

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)
);

表數據文件(data-h2.sql)內容:

INSERT INTO user (id, name, age, email) VALUES
(1, 'neo', 18, '[email protected]'),
(2, 'keep', 36, '[email protected]'),
(3, 'pure', 28, '[email protected]'),
(4, 'smile', 21, '[email protected]'),
(5, 'it', 24, '[email protected]');

在示例項目的 resources 目錄下創建 db 文件夾,將兩個文件放入其中。

添加依賴

添加相關依賴包,pom.xml 中的相關依賴內容如下:

<dependencies>
	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<optional>true</optional>
	</dependency>
	<dependency>
		<groupId>com.baomidou</groupId>
		<artifactId>mybatis-plus-boot-starter</artifactId>
		<version>3.1.1</version>
	</dependency>
	<dependency>
		<groupId>com.h2database</groupId>
		<artifactId>h2</artifactId>
		<scope>runtime</scope>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>
  • lombok,幫忙省略掉 Get/Set 方法,具體可以參考這篇文章
  • mybatis-plus-boot-starter,MyBatis Plus 的依賴包
  • h2,本次測試我們使用內存數據庫 h2 來演示。
  • spring-boot-starter-test,Spring Boot 的測試包

配置文件

# DataSource Config
spring:
    datasource:
        driver-class-name: org.h2.Driver
        schema: classpath:db/schema-h2.sql
        data: classpath:db/data-h2.sql
        url: jdbc:h2:mem:test
        username: root
        password: test

# Logger Config
logging:
    level:
      com.neo: debug

配置了 h2 數據庫,已經項目的日誌級別。配置 schema 和 data 後,項目啓動時會根據配置的文件地址來執行數據。

業務代碼

創建 MybatisPlusConfig 類,指定 Mapper 地址,啓用分頁功能。

@Configuration
@MapperScan("com.neo.mapper")
public class MybatisPlusConfig {

    /**
     * 分頁插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

創建實體類 User

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

@Data 爲 lombok 語法,自動注入 getter/setter 方法。

接下來創建對象對於的 Mapper。

public interface UserMapper extends BaseMapper<User> {
}

以上業務代碼就開發完成了,是不是很簡單。

測試

創建 MyBatisPlusTest 類,注入上面創建的 UserMapper 類。

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyBatisPlusTest {
    @Autowired
    private UserMapper userMapper;
}

測試查詢單挑數據,並輸出

@Test
public void testSelectOne() {
    User user = userMapper.selectById(1L);
    System.out.println(user);
}

測試添加數據

@Test
public void testInsert() {
    User user = new User();
    user.setName("微笑");
    user.setAge(3);
    user.setEmail("[email protected]");
    assertThat(userMapper.insert(user)).isGreaterThan(0);
    // 成功直接拿會寫的 ID
    assertThat(user.getId()).isNotNull();
}

assertThat() 是 Assert 的一個精通方法,用來比對返回結果,包來自import static org.assertj.core.api.Assertions.assertThat;

測試刪除數據

@Test
public void testDelete() {
    assertThat(userMapper.deleteById(3L)).isGreaterThan(0);
    assertThat(userMapper.delete(new QueryWrapper<User>()
            .lambda().eq(User::getName, "smile"))).isGreaterThan(0);
}

QueryWrapper 是 MyBatis-Plus 內部輔助查詢類,可以使用 lambda 語法,也可以不使用。利用 QueryWrapper 類可以構建各種查詢條件。

測試更新數據

@Test
public void testUpdate() {
    User user = userMapper.selectById(2);
    assertThat(user.getAge()).isEqualTo(36);
    assertThat(user.getName()).isEqualTo("keep");

    userMapper.update(
            null,
            Wrappers.<User>lambdaUpdate().set(User::getEmail, "123@123").eq(User::getId, 2)
    );
    assertThat(userMapper.selectById(2).getEmail()).isEqualTo("123@123");
}

測試查詢所有數據

@Test
public void testSelect() {
    List<User> userList = userMapper.selectList(null);
    Assert.assertEquals(5, userList.size());
    userList.forEach(System.out::println);
}

測試非分頁查詢

@Test
public void testPage() {
    System.out.println("----- baseMapper 自帶分頁 ------");
    Page<User> page = new Page<>(1, 2);
    IPage<User> userIPage = userMapper.selectPage(page, new QueryWrapper<User>()
            .gt("age", 6));
    assertThat(page).isSameAs(userIPage);
    System.out.println("總條數 ------> " + userIPage.getTotal());
    System.out.println("當前頁數 ------> " + userIPage.getCurrent());
    System.out.println("當前每頁顯示數 ------> " + userIPage.getSize());
    print(userIPage.getRecords());
    System.out.println("----- baseMapper 自帶分頁 ------");
}

查詢大於 6 歲的用戶,並且分頁展示,每頁兩條數據,展示第一頁。

總結

簡單使用了一下 MyBatis-Plus 感覺是一款挺不錯的 MyBatis 插件,使用 MyBatis-Plus 操作數據庫確實可以少寫一些代碼,另外 MyBatis-Plus 的功能比較豐富,文中僅展示了常用的增刪改查和分頁查詢,如果想進一步學習可以關注官網示例。

示例代碼

全網最全的 Spring Boot 學習示例項目,擊下方鏈接即可獲取。

示例代碼-github

示例代碼-碼雲

參考出處:

https://mp.baomidou.com/guide

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章