一匕争、前言
本文小編將基于 SpringBoot
整合 MyBatis-Plus
, MyBatis-Plus 是一個(gè) MyBatis 的增強(qiáng)工具胆描,在 MyBatis 的基礎(chǔ)上做增強(qiáng)并且不改變?cè)竟δ?~
二计雌、SpringBoot整合MyBatis-Plus
基本環(huán)境
- spring-boot 2.1.8
- mybatis-plus 2.2.0
- mysql 5.7.24
- maven項(xiàng)目
1昧谊、pom.xml
中引入MyBatis-Plus
相關(guān)依賴
下面直接貼出小編的整個(gè)文件內(nèi)容以作參考,避免因?yàn)椴糠旨?xì)節(jié)缺失導(dǎo)致錯(cuò)誤
<?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 -->
<!-- ========================= 數(shù)據(jù)庫(kù)相關(guān) ========================== -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- 阿里數(shù)據(jù)庫(kù)連接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.18</version>
</dependency>
<!-- ========================= 常用庫(kù)依賴 ========================== -->
<!-- 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默認(rèn)是不編譯鸽斟,因此加上如下resources才會(huì)生產(chǎn)對(duì)應(yīng)的xml文件 目的:解決mybatis映射關(guān)系不對(duì)應(yīng)問(wèn)題 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默認(rèn)是不編譯拔创,因此加上如下resources才會(huì)生產(chǎn)對(duì)應(yīng)的xml文件 目的:解決mybatis映射關(guān)系不對(duì)應(yīng)問(wèn)題 end =============== -->
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、MyBatis-Plus配置類
這里主要配置分頁(yè)插件 和 @MapperScan注解掃描 Mapper 文件夾
@EnableTransactionManagement
@Configuration
@MapperScan("com.zhengqing.demo.modules.**.mapper*") // 掃描 Mapper 文件夾 【注:根據(jù)自己的項(xiàng)目結(jié)構(gòu)配置】
public class MybatisPlusConfig {
/**
* mybatis-plus分頁(yè)插件<br>
* 文檔:https://mp.baomidou.com/guide/page.html <br>
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
3富蓄、application.yml
中配置數(shù)據(jù)庫(kù)以及mybatis-plus相關(guān)配置
溫馨小提示:注意修改自己的數(shù)據(jù)庫(kù)連接配置信息哦~
# 配置端口
server:
port: 8080
servlet:
# context-path: /api
application-display-name: demo
spring:
application:
name: demo
profiles:
active: dev
# 配置數(shù)據(jù)源
datasource:
url: jdbc:mysql://127.0.0.1:3306/demo?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false # MySQL在高版本需要指明是否進(jìn)行SSL連接 解決則加上 &useSSL=false
name: demo
username: root
password: root
# 使用druid數(shù)據(jù)源
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相關(guān)配置
mybatis-plus:
# xml掃描剩燥,多個(gè)目錄用逗號(hào)或者分號(hào)分隔(告訴 Mapper 所對(duì)應(yīng)的 XML 文件位置)
mapper-locations: classpath:**/*Mapper.xml
# 以下配置均有默認(rèn)值,可以不設(shè)置
global-config:
#主鍵類型 0:"數(shù)據(jù)庫(kù)ID自增", 1:"用戶輸入ID",2:"全局唯一ID (數(shù)字類型唯一ID)", 3:"全局唯一ID UUID";
id-type: 0
#字段策略 0:"忽略判斷",1:"非 NULL 判斷"),2:"非空判斷"
field-strategy: 2
#駝峰下劃線轉(zhuǎn)換
db-column-underline: true
#刷新mapper 調(diào)試神器
refresh-mapper: false
#數(shù)據(jù)庫(kù)大寫(xiě)下劃線轉(zhuǎn)換
#capital-mode: true
#序列接口實(shí)現(xiàn)類配置
#key-generator: com.baomidou.springboot.xxx
#邏輯刪除配置
#logic-delete-value: 0 # 邏輯已刪除值(默認(rèn)為 1)
#logic-not-delete-value: 1 # 邏輯未刪除值(默認(rèn)為 0)
#自定義填充策略接口實(shí)現(xiàn)
# meta-object-handler: com.zhengqing.config.MyMetaObjectHandler
#自定義SQL注入器
#sql-injector: com.baomidou.springboot.xxx
configuration:
# 是否開(kāi)啟自動(dòng)駝峰命名規(guī)則映射:從數(shù)據(jù)庫(kù)列名到Java屬性駝峰命名的類似映射
map-underscore-to-camel-case: true
cache-enabled: false
# 如果查詢結(jié)果中包含空值的列,則 MyBatis 在映射的時(shí)候立倍,不會(huì)映射這個(gè)字段
# call-setters-on-nulls: true
# 這個(gè)配置會(huì)將執(zhí)行的sql打印出來(lái)灭红,在開(kāi)發(fā)或測(cè)試的時(shí)候可以用
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 解決oracle更新數(shù)據(jù)為null時(shí)無(wú)法轉(zhuǎn)換報(bào)錯(cuò),mysql不會(huì)出現(xiàn)此情況
jdbc-type-for-null: 'null'
三口注、模擬業(yè)務(wù)代碼 - 對(duì)用戶信息表做CRUD
1变擒、數(shù)據(jù)庫(kù)新建t_sys_user
用戶表
2、編寫(xiě)實(shí)體類
溫馨小提示 : 實(shí)體類繼承MyBatis-Plus的
Model
類 +Mapper
類繼承MyBatis-Plus的BaseMapper
類 -> 可支持ActiveRecord
動(dòng)態(tài)語(yǔ)法調(diào)用
@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;
/**
* 賬號(hào)
*/
@TableField("username")
private String username;
/**
* 登錄密碼
*/
@TableField("password")
private String password;
/**
* 昵稱
*/
@TableField("nick_name")
private String nickName;
@Override
protected Serializable pkVal() {
return this.id;
}
}
3寝志、編寫(xiě)Mapper類
public interface UserMapper extends BaseMapper<User> { }
四娇斑、測(cè)試CRUD
溫馨小提示:以下CRUD均采用 ActiveRecord 動(dòng)態(tài)語(yǔ)法
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
/**
* 新增數(shù)據(jù)
*/
@Test
public void testAdd() throws Exception{
User entity = new User();
entity.setUsername("admin");
entity.setPassword("123456");
entity.setNickName("管理員");
entity.insert();
}
/**
* 更新數(shù)據(jù)
*/
@Test
public void testUpdate() throws Exception{
User entity = new User();
entity.setId(1);
entity.setUsername("test");
entity.setPassword("123456");
entity.setNickName("測(cè)試號(hào)");
entity.updateById();
}
/**
* 刪除數(shù)據(jù)
*/
@Test
public void testDelete() throws Exception{
User entity = new User();
entity.deleteById(1);
}
/**
* 查詢指定id數(shù)據(jù)
*/
@Test
public void testSelectById() throws Exception{
User entity = new User();
User user = entity.selectById(1);
System.out.println(user);
}
/**
* 查詢所有數(shù)據(jù)
*/
@Test
public void testSelectAll() throws Exception{
User entity = new User();
List list = entity.selectList(null);
System.out.println(list);
}
/**
* 查詢所有數(shù)據(jù) - 分頁(yè)
*/
@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方式
這個(gè)案例就放文末demo源碼吧材部,不多說(shuō)毫缆,也就是自己寫(xiě)sql語(yǔ)句處理對(duì)應(yīng)業(yè)務(wù)
六、總結(jié)
- 引入相關(guān)依賴
- MyBatis-Plus核心配置 - 掃包乐导、別名苦丁、分頁(yè)插件等
- 編寫(xiě)業(yè)務(wù)代碼測(cè)試
總體來(lái)說(shuō)相對(duì)簡(jiǎn)單,關(guān)于MyBatis-Plus更多的語(yǔ)法和功能可參考MyBatis-Plus官網(wǎng)文檔
https://mp.baomidou.com/guide/crud-interface.html#mapper-crud-%E6%8E%A5%E5%8F%A3
整體項(xiàng)目結(jié)構(gòu):
本文案例源碼
https://gitee.com/zhengqingya/java-workspace