該項(xiàng)目源碼地址:https://github.com/ggb2312/JavaNotes/tree/master/springboot-integration-examples (其中包含SpringBoot和其他常用技術(shù)的整合邀窃,配套源碼以及筆記孕似。基于最新的 SpringBoot2.1+,歡迎各位 Star)
1. 開(kāi)發(fā)前準(zhǔn)備
1.1 前置知識(shí)
- java基礎(chǔ)
- SpringBoot簡(jiǎn)單基礎(chǔ)知識(shí)
1.2 環(huán)境參數(shù)
- 開(kāi)發(fā)工具:IDEA
- 基礎(chǔ)環(huán)境:Maven+JDK8
- 所用技術(shù):SpringBoot级遭、lombok、MybatisPlus
- SpringBoot版本:2.1.4
1.3 涉及知識(shí)點(diǎn)
- MybatisPlus簡(jiǎn)介洛波、特性巩搏、架構(gòu)
- MybatisPlus快速入門
- MybatisPlus的基本CRUD
- MybatisPlus的高級(jí)查詢:like查詢、條件查詢播演、分頁(yè)查詢等
2. MybatisPlus入門
2.1 簡(jiǎn)介
MyBatis-Plus(簡(jiǎn)稱 MP)是一個(gè) MyBatis 的增強(qiáng)工具冀瓦,在 MyBatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開(kāi)發(fā)写烤、提高效率而生翼闽。
2.2 特性
- 無(wú)侵入:只做增強(qiáng)不做改變,引入它不會(huì)對(duì)現(xiàn)有工程產(chǎn)生影響洲炊,如絲般順滑
- 損耗小:?jiǎn)?dòng)即會(huì)自動(dòng)注入基本 CURD感局,性能基本無(wú)損耗尼啡,直接面向?qū)ο蟛僮?/li>
- 強(qiáng)大的 CRUD 操作:內(nèi)置通用 Mapper、通用 Service询微,僅僅通過(guò)少量配置即可實(shí)現(xiàn)單表大部分 CRUD 操作崖瞭,更有強(qiáng)大的條件構(gòu)造器,滿足各類使用需求
- 支持 Lambda 形式調(diào)用:通過(guò) Lambda 表達(dá)式撑毛,方便的編寫(xiě)各類查詢條件书聚,無(wú)需再擔(dān)心字段寫(xiě)錯(cuò)
- 支持多種數(shù)據(jù)庫(kù):支持 MySQL、MariaDB代态、Oracle寺惫、DB2、H2蹦疑、HSQL西雀、SQLite、Postgre歉摧、SQLServer2005艇肴、SQLServer 等多種數(shù)據(jù)庫(kù)
- 支持主鍵自動(dòng)生成:支持多達(dá) 4 種主鍵策略(內(nèi)含分布式唯一 ID 生成器 - Sequence),可自由配置叁温,完美解決主鍵問(wèn)題
- 支持 XML 熱加載:Mapper 對(duì)應(yīng)的 XML 支持熱加載再悼,對(duì)于簡(jiǎn)單的 CRUD 操作,甚至可以無(wú) XML 啟動(dòng)
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式調(diào)用,實(shí)體類只需繼承 Model 類即可進(jìn)行強(qiáng)大的 CRUD 操作
- 支持自定義全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 支持關(guān)鍵詞自動(dòng)轉(zhuǎn)義:支持?jǐn)?shù)據(jù)庫(kù)關(guān)鍵詞(order、key......)自動(dòng)轉(zhuǎn)義器罐,還可自定義關(guān)鍵詞
- 內(nèi)置代碼生成器:采用代碼或者 Maven 插件可快速生成 Mapper 、 Model 莺奸、 Service 、 Controller 層代碼冀宴,支持模板引擎灭贷,更有超多自定義配置等您來(lái)使用
- 內(nèi)置分頁(yè)插件:基于 MyBatis 物理分頁(yè),開(kāi)發(fā)者無(wú)需關(guān)心具體操作略贮,配置好插件之后甚疟,寫(xiě)分頁(yè)等同于普通 List 查詢
- 內(nèi)置性能分析插件:可輸出 Sql 語(yǔ)句以及其執(zhí)行時(shí)間,建議開(kāi)發(fā)測(cè)試時(shí)啟用該功能逃延,能快速揪出慢查詢
- 內(nèi)置全局?jǐn)r截插件:提供全表 delete 览妖、 update 操作智能分析阻斷,也可自定義攔截規(guī)則真友,預(yù)防誤操作
- 內(nèi)置 Sql 注入剝離器:支持 Sql 注入剝離黄痪,有效預(yù)防 Sql 注入攻擊
2.3 架構(gòu)
2.4 快速入門
項(xiàng)目結(jié)構(gòu):
2.4.1 創(chuàng)建表
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)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
2.4.2 創(chuàng)建工程以及導(dǎo)入依賴
<dependencies>
<!--簡(jiǎn)化代碼的工具包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--mybatis-plus的springboot支持-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<!--mysql驅(qū)動(dòng)-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
2.4.3 編寫(xiě)application.properties文件
spring.application.name = lastwhisper-mybatis-plus
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatisplus?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
2.4.4 創(chuàng)建User對(duì)象
package cn.lastwhisper.springbootmybatisplus.pojo;
import lombok.Data;
import lombok.ToString;
/**
* @desc
*
* @author lastwhisper
* @email gaojun56@163.com
*/
@Data
@ToString
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
2.4.5 編寫(xiě)UserMapper
package cn.lastwhisper.springbootmybatisplus.mapper;
import cn.lastwhisper.springbootmybatisplus.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* @desc
*
* @author lastwhisper
* @email gaojun56@163.com
*/
public interface UserMapper extends BaseMapper<User> {
}
2.4.6 設(shè)置Mapper接口的包掃描
修改SpringBoot啟動(dòng)類
package cn.lastwhisper.springbootmybatisplus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("cn.lastwhisper.springbootmybatisplus.mapper") //設(shè)置mapper接口的掃描包
@SpringBootApplication
public class SpringbootmybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootmybatisplusApplication.class, args);
}
}
2.4.7 編寫(xiě)測(cè)試單元
package cn.lastwhisper.springbootmybatisplus;
import cn.lastwhisper.springbootmybatisplus.mapper.UserMapper;
import cn.lastwhisper.springbootmybatisplus.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootmybatisplusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
for (User user : userList) {
System.out.println(user);
}
}
}
2.5 BaseMapper
在MybatisPlus中,BaseMapper中定義了一些常用的CRUD方法盔然,當(dāng)我們自定義的Mapper接口繼承BaseMapper后即可擁有了這些方法桅打。
需要說(shuō)明的是:這些方法僅適合單表操作。
BaseMapper接口的代碼如下
/**
* Mapper 繼承該接口后愈案,無(wú)需編寫(xiě) mapper.xml 文件挺尾,即可獲得CRUD功能
* <p>這個(gè) Mapper 支持 id 泛型</p>
*
* @author hubin
* @since 2016-01-23
*/
public interface BaseMapper<T> extends Mapper<T> {
/**
* 插入一條記錄
*
* @param entity 實(shí)體對(duì)象
*/
int insert(T entity);
/**
* 根據(jù) ID 刪除
*
* @param id 主鍵ID
*/
int deleteById(Serializable id);
/**
* 根據(jù) columnMap 條件,刪除記錄
*
* @param columnMap 表字段 map 對(duì)象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根據(jù) entity 條件站绪,刪除記錄
*
* @param wrapper 實(shí)體對(duì)象封裝操作類(可以為 null)
*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
/**
* 刪除(根據(jù)ID 批量刪除)
*
* @param idList 主鍵ID列表(不能為 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 根據(jù) ID 修改
*
* @param entity 實(shí)體對(duì)象
*/
int updateById(@Param(Constants.ENTITY) T entity);
/**
* 根據(jù) whereEntity 條件遭铺,更新記錄
*
* @param entity 實(shí)體對(duì)象 (set 條件值,可以為 null)
* @param updateWrapper 實(shí)體對(duì)象封裝操作類(可以為 null,里面的 entity 用于生成 where 語(yǔ)句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
/**
* 根據(jù) ID 查詢
*
* @param id 主鍵ID
*/
T selectById(Serializable id);
/**
* 查詢(根據(jù)ID 批量查詢)
*
* @param idList 主鍵ID列表(不能為 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 查詢(根據(jù) columnMap 條件)
*
* @param columnMap 表字段 map 對(duì)象
*/
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根據(jù) entity 條件,查詢一條記錄
*
* @param queryWrapper 實(shí)體對(duì)象封裝操作類(可以為 null)
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根據(jù) Wrapper 條件恢准,查詢總記錄數(shù)
*
* @param queryWrapper 實(shí)體對(duì)象封裝操作類(可以為 null)
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根據(jù) entity 條件魂挂,查詢?nèi)坑涗? *
* @param queryWrapper 實(shí)體對(duì)象封裝操作類(可以為 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根據(jù) Wrapper 條件,查詢?nèi)坑涗? *
* @param queryWrapper 實(shí)體對(duì)象封裝操作類(可以為 null)
*/
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根據(jù) Wrapper 條件馁筐,查詢?nèi)坑涗? * <p>注意: 只返回第一個(gè)字段的值</p>
*
* @param queryWrapper 實(shí)體對(duì)象封裝操作類(可以為 null)
*/
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根據(jù) entity 條件涂召,查詢?nèi)坑涗洠ú⒎?yè))
*
* @param page 分頁(yè)查詢條件(可以為 RowBounds.DEFAULT)
* @param queryWrapper 實(shí)體對(duì)象封裝操作類(可以為 null)
*/
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根據(jù) Wrapper 條件,查詢?nèi)坑涗洠ú⒎?yè))
*
* @param page 分頁(yè)查詢條件
* @param queryWrapper 實(shí)體對(duì)象封裝操作類
*/
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}
2.5.1 like查詢
@Test
public void testselectByLike() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>(new User());
// 查詢名字中包含"o"的用戶
queryWrapper.like("name", "o");
List<User> users = this.userMapper.selectList(queryWrapper);
for (User user : users) {
System.out.println(user);
}
}
測(cè)試結(jié)果:
2.5.2 條件查詢
// 條件查詢
@Test
public void testselectByLe(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>(new User());
//查詢年齡小于等于20的用戶
queryWrapper.le("age",20);
List<User> users = this.userMapper.selectList(queryWrapper);
for (User user:users) {
System.out.println(user);
}
}
測(cè)試結(jié)果:
更多查看:http://mp.baomidou.com/guide/wrapper.html#abstractwrapper
2.5.3 插入數(shù)據(jù)
數(shù)據(jù)庫(kù)主鍵自增: @TableId(value = "ID", type = IdType.AUTO)
數(shù)據(jù)庫(kù)主鍵自己維護(hù):@TableId(value = "open_id",type = IdType.INPUT)
設(shè)置主鍵自增長(zhǎng)
@Data
@ToString
public class User {
@TableId(value = "ID", type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
設(shè)置表主鍵自增
測(cè)試代碼
//插入數(shù)據(jù)
@Test
public void testSave(){
User user = new User();
user.setAge(21);
user.setEmail("gaojun56@163.com");
user.setName("gaojun");
int count = this.userMapper.insert(user);
System.out.println("新增數(shù)據(jù)成功! count => " + count);
}
測(cè)試結(jié)果:
數(shù)據(jù)庫(kù):
2.5.4 刪除數(shù)據(jù)
//刪除數(shù)據(jù)
@Test
public void testDelete(){
this.userMapper.deleteById(6L);
System.out.println("刪除成功!");
}
測(cè)試結(jié)果:
2.5.5 修改數(shù)據(jù)
根據(jù)id修改數(shù)據(jù)敏沉,修改不為null的字段
//修改數(shù)據(jù)
@Test
public void testUpdate(){
User user = new User();
user.setId(5L);
user.setName("gaojun");
user.setEmail("gaojun56@163.com");
this.userMapper.updateById(user);
System.out.println("修改成功!");
}
測(cè)試結(jié)果:
2.5.6 分頁(yè)查詢
首先在SpringBoot啟動(dòng)類中配置分頁(yè)插件
@MapperScan("cn.lastwhisper.springbootmybatisplus.mapper") //設(shè)置mapper接口的掃描包
@SpringBootApplication
public class SpringbootmybatisplusApplication {
/**
* 分頁(yè)插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
public static void main(String[] args) {
SpringApplication.run(SpringbootmybatisplusApplication.class, args);
}
}
測(cè)試類:
//分頁(yè)查詢
@Test
public void testselectPage() {
Page<User> page = new Page<>(1, 2);
IPage<User> userIPage = this.userMapper.selectPage(page, null);
System.out.println("總條數(shù) ------> " + userIPage.getTotal());
System.out.println("當(dāng)前頁(yè)數(shù) ------> " + userIPage.getCurrent());
System.out.println("當(dāng)前每頁(yè)顯示數(shù) ------> " + userIPage.getSize());
List<User> records = userIPage.getRecords();
for (User user : records) {
System.out.println(user);
}
}
測(cè)試結(jié)果:
2.6 配置
雖然在MybatisPlus中可以實(shí)現(xiàn)零配置果正,但是有些時(shí)候需要我們自定義一些配置,就需要使用Mybatis原生的一些配置文件方式了盟迟。
application.properties:
# 指定全局配置文件
mybatis-plus.config-location = classpath:mybatis-config.xml
# 指定mapper.xml文件
mybatis-plus.mapper-locations = classpath*:mybatis/*.xml