您好,登錄后才能下訂單哦!
本文小編將基于 SpringBoot
整合 MyBatis-Plus
, MyBatis-Plus 是一個(gè) MyBatis 的增強(qiáng)工具,在 MyBatis 的基礎(chǔ)上做增強(qiáng)并且不改變?cè)竟δ?~
pom.xml
中引入MyBatis-Plus
相關(guān)依賴(lài)下面直接貼出小編的整個(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ù)依賴(lài) ========================== -->
<!-- lombok插件 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Hutool工具類(lèi) -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool-all.version}</version>
</dependency>
<!-- StringUtils工具類(lèi) -->
<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>
這里主要配置分頁(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();
}
}
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:
#主鍵類(lèi)型 0:"數(shù)據(jù)庫(kù)ID自增", 1:"用戶輸入ID",2:"全局唯一ID (數(shù)字類(lèi)型唯一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)類(lèi)配置
#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屬性駝峰命名的類(lèi)似映射
map-underscore-to-camel-case: true
cache-enabled: false
# 如果查詢(xún)結(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'
t_sys_user
用戶表溫馨小提示 : 實(shí)體類(lèi)繼承MyBatis-Plus的
Model
類(lèi) +Mapper
類(lèi)繼承MyBatis-Plus的BaseMapper
類(lèi) -> 可支持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;
/**
* 昵稱(chēng)
*/
@TableField("nick_name")
private String nickName;
@Override
protected Serializable pkVal() {
return this.id;
}
}
public interface UserMapper extends BaseMapper<User> { }
溫馨小提示:以下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);
}
/**
* 查詢(xún)指定id數(shù)據(jù)
*/
@Test
public void testSelectById() throws Exception{
User entity = new User();
User user = entity.selectById(1);
System.out.println(user);
}
/**
* 查詢(xún)所有數(shù)據(jù)
*/
@Test
public void testSelectAll() throws Exception{
User entity = new User();
List list = entity.selectList(null);
System.out.println(list);
}
/**
* 查詢(xún)所有數(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);
}
}
這個(gè)案例就放文末demo源碼吧,不多說(shuō),也就是自己寫(xiě)sql語(yǔ)句處理對(duì)應(yīng)業(yè)務(wù)
總體來(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
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。