SpringBoot 整合 MyBatis-Plus 入門體驗
阿新 • • 發佈:2019-12-31
一、前言
本文小編將基於 SpringBoot
整合 MyBatis-Plus
, MyBatis-Plus 是一個 MyBatis 的增強工具,在 MyBatis 的基礎上做增強並且不改變原本功能 ~
二、SpringBoot整合MyBatis-Plus
基本環境
- spring-boot 2.1.8
- mybatis-plus 2.2.0
- mysql 5.7.24
- maven專案
1、pom.xml
中引入MyBatis-Plus
相關依賴
下面直接貼出小編的整個檔案內容以作參考,避免因為部分細節缺失導致錯誤
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId >
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zhengqing</groupId>
<artifactId>demo</artifactId >
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<mybatis-plus-boot-starter.version>2.2.0</mybatis-plus-boot-starter.version>
<mysql.version>5.1.40</mysql.version>
<commons-lang3.version>3.6</commons-lang3.version>
<hutool-all.version>4.6.2</hutool-all.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mybatis-plus begin =================================== -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus-boot-starter.version}</version>
</dependency>
<!-- mybatis-plus end -->
<!-- ========================= 資料庫相關 ========================== -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- 阿里資料庫連線池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.18</version>
</dependency>
<!-- ========================= 常用庫依賴 ========================== -->
<!-- lombok外掛 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Hutool工具類 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool-all.version}</version>
</dependency>
<!-- StringUtils工具類 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
<build>
<!-- 注:maven預設是不編譯,因此加上如下resources才會生產對應的xml檔案 目的:解決mybatis對映關係不對應問題 start =============== -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</testResource>
</testResources>
<!-- 注:maven預設是不編譯,因此加上如下resources才會生產對應的xml檔案 目的:解決mybatis對映關係不對應問題 end =============== -->
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
複製程式碼
2、MyBatis-Plus配置類
這裡主要配置分頁外掛 和 @MapperScan註解掃描 Mapper 資料夾
@EnableTransactionManagement
@Configuration
@MapperScan("com.zhengqing.demo.modules.**.mapper*") // 掃描 Mapper 資料夾 【注:根據自己的專案結構配置】
public class MybatisPlusConfig {
/**
* mybatis-plus分頁外掛<br>
* 檔案:https://mp.baomidou.com/guide/page.html <br>
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
複製程式碼
3、application.yml
中配置資料庫以及mybatis-plus相關配置
溫馨小提示:注意修改自己的資料庫連線配置資訊哦~
# 配置埠
server:
port: 8080
servlet:
# context-path: /api
application-display-name: demo
spring:
application:
name: demo
profiles:
active: dev
# 配置資料來源
datasource:
url: jdbc:mysql://127.0.0.1:3306/demo?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false # MySQL在高版本需要指明是否進行SSL連線 解決則加上 &useSSL=false
name: demo
username: root
password: root
# 使用druid資料來源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
management:
security:
enabled: false
# mybatis-plus相關配置
mybatis-plus:
# xml掃描,多個目錄用逗號或者分號分隔(告訴 Mapper 所對應的 XML 檔案位置)
mapper-locations: classpath:**/*Mapper.xml
# 以下配置均有預設值,可以不設定
global-config:
#主鍵型別 0:"資料庫ID自增",1:"使用者輸入ID",2:"全域性唯一ID (數字型別唯一ID)",3:"全域性唯一ID UUID";
id-type: 0
#欄位策略 0:"忽略判斷",1:"非 NULL 判斷"),2:"非空判斷"
field-strategy: 2
#駝峰下劃線轉換
db-column-underline: true
#重新整理mapper 除錯神器
refresh-mapper: false
#資料庫大寫下劃線轉換
#capital-mode: true
#序列介面實現類配置
#key-generator: com.baomidou.springboot.xxx
#邏輯刪除配置
#logic-delete-value: 0 # 邏輯已刪除值(預設為 1)
#logic-not-delete-value: 1 # 邏輯未刪除值(預設為 0)
#自定義填充策略介面實現
# meta-object-handler: com.zhengqing.config.MyMetaObjectHandler
#自定義SQL注入器
#sql-injector: com.baomidou.springboot.xxx
configuration:
# 是否開啟自動駝峰命名規則對映:從資料庫列名到Java屬性駝峰命名的類似對映
map-underscore-to-camel-case: true
cache-enabled: false
# 如果查詢結果中包含空值的列,則 MyBatis 在對映的時候,不會對映這個欄位
# call-setters-on-nulls: true
# 這個配置會將執行的sql打印出來,在開發或測試的時候可以用
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 解決oracle更新資料為null時無法轉換報錯,mysql不會出現此情況
jdbc-type-for-null: 'null'
複製程式碼
三、模擬業務程式碼 - 對使用者資訊表做CRUD
1、資料庫新建t_sys_user
使用者表
2、編寫實體類
溫馨小提示 : 實體類繼承MyBatis-Plus的
Model
類 +Mapper
類繼承MyBatis-Plus的BaseMapper
類 -> 可支援ActiveRecord
動態語法呼叫
@Data
@TableName("t_sys_user")
public class User extends Model<User> {
private static final long serialVersionUID = 1L;
/**
* 主鍵ID
*/
@TableId(value="id",type= IdType.AUTO)
private Integer id;
/**
* 賬號
*/
@TableField("username")
private String username;
/**
* 登入密碼
*/
@TableField("password")
private String password;
/**
* 暱稱
*/
@TableField("nick_name")
private String nickName;
@Override
protected Serializable pkVal() {
return this.id;
}
}
複製程式碼
3、編寫Mapper類
public interface UserMapper extends BaseMapper<User> { }
複製程式碼
四、測試CRUD
溫馨小提示:以下CRUD均採用 ActiveRecord 動態語法
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
/**
* 新增資料
*/
@Test
public void testAdd() throws Exception{
User entity = new User();
entity.setUsername("admin");
entity.setPassword("123456");
entity.setNickName("管理員");
entity.insert();
}
/**
* 更新資料
*/
@Test
public void testUpdate() throws Exception{
User entity = new User();
entity.setId(1);
entity.setUsername("test");
entity.setPassword("123456");
entity.setNickName("測試號");
entity.updateById();
}
/**
* 刪除資料
*/
@Test
public void testDelete() throws Exception{
User entity = new User();
entity.deleteById(1);
}
/**
* 查詢指定id資料
*/
@Test
public void testSelectById() throws Exception{
User entity = new User();
User user = entity.selectById(1);
System.out.println(user);
}
/**
* 查詢所有資料
*/
@Test
public void testSelectAll() throws Exception{
User entity = new User();
List list = entity.selectList(null);
System.out.println(list);
}
/**
* 查詢所有資料 - 分頁
*/
@Test
public void testSelectAllPage() throws Exception{
User entity = new User();
Page<User> page = entity.selectPage(new Page<User>(1,10),null);
System.out.println(page);
}
}
複製程式碼
五、原生MyBatis方式
這個案例就放文末demo原始碼吧,不多說,也就是自己寫sql語句處理對應業務
六、總結
- 引入相關依賴
- MyBatis-Plus核心配置 - 掃包、別名、分頁外掛等
- 編寫業務程式碼測試
總體來說相對簡單,關於MyBatis-Plus更多的語法和功能可參考MyBatis-Plus官網檔案
整體專案結構: