《MybatisPlus—為簡化開發而生》
文章目錄
- 《MybatisPlus—為簡化開發而生》
- 1、簡介
- 2、特性
- 3、快速入門
- 1、創建資料庫`mybatis-plus`
- 2、創建user表
- 3、撰寫專案,初始化專案,使用SpringBoot初始化
- 4、匯入依賴
- 5、連接資料庫
- 6、使用MybatisPlus
- 4、配置日志輸出
- 5、插入測驗及雪花演算法
- 6、CRUD擴展
- 1、插入操作
- 2、主鍵生成策略
- 3、更新操作
- 4、自動填充
- 5、樂觀鎖
- 7、查詢操作
- 8、分頁查詢
- 9、洗掉操作
- 9、邏輯洗掉
- 10.性能分析插件
- 11、條件查詢器Wrapper
- 1、測驗一:
- 2、測驗二
- 3、測驗三
- 4、測驗四
- 5、測驗五
- 6、測驗六
- 12、代碼生成器
官網:https://www.sogou.com/link?url=58p16RfDRLuiEHkXxtCPmEiZEcHfFSzq

1、簡介
MyBatis-Plus (opens new window)(簡稱 MP)是一個 MyBatis (opens new window)的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生,
2、特性
- 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
- 損耗小:啟動即會自動注入基本 CURD,性能基本無損耗,直接面向物件操作,BaseMapper
- 強大的 CRUD 操作:內置通用 Mapper、通用 Service,僅僅通過少量配置即可實作單表大部分 CRUD 操作,更有強大的條件構造器,滿足各類使用需求(以后基本的CRUD不用自己撰寫)
- 支持 Lambda 形式呼叫:通過 Lambda 運算式,方便的撰寫各類查詢條件,無需再擔心欄位寫錯
- 支持主鍵自動生成:支持多達 4 種主鍵策略(內含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解決主鍵問題
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式呼叫,物體類只需繼承 Model 類即可進行強大的 CRUD 操作
- 支持自定義全域通用操作:支持全域通用方法注入( Write once, use anywhere )
- 內置代碼生成器:采用代碼或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 層代碼,支持模板引擎,更有超多自定義配置等您來使用(自動生成代碼)
- 內置分頁插件:基于 MyBatis 物理分頁,開發者無需關心具體操作,配置好插件之后,寫分頁等同于普通 List 查詢
- 分頁插件支持多種資料庫:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多種資料庫
- 內置性能分析插件:可輸出 SQL 陳述句以及其執行時間,建議開發測驗時啟用該功能,能快速揪出慢查詢
- 內置全域攔截插件:提供全表 delete 、 update 操作智能分析阻斷,也可自定義攔截規則,預防誤操作
3、快速入門
地址:https://mp.baomidou.com/guide/quick-start.html#%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B7%A5%E7%A8%8B
使用第三方組件:
1、匯入對應的依賴
2、研究依賴如何配置
3、代碼如何撰寫
4、提高擴展技術能力
步驟
1、創建資料庫mybatis-plus

2、創建user表
| id | name | age | |
|---|---|---|---|
| 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 |
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)
);
-- 真實開發中 version(樂觀鎖) deleted(邏輯洗掉) gmt_create gmt_modified
其對應的資料庫 Data 腳本如下:
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');
3、撰寫專案,初始化專案,使用SpringBoot初始化

4、匯入依賴
<!-- 連接資料庫-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus-->
<!-- mybatis-plus 是自己開發的,并非官方的-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.3</version>
</dependency>
說明:mybatis以及mybatis-plus這兩個包不能同時匯入
5、連接資料庫
#mybatis 5 com.mysql.jdbc.Driver
#mybatis 8 需要加上時區 、com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&character=UTF-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
傳統方式:6、pojo-dao(連接mybatis、配置mapper.xml檔案)-service-controller
6、使用MybatisPlus
- pojo
#mybatis 5 com.mysql.jdbc.Driver
#mybatis 8 需要加上時區 、com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&character=UTF-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- mapper介面
package com.kk.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kk.pojo.User;
import org.springframework.stereotype.Repository;
import java.util.List;
// 在對應的Mapper 上面實作基本的介面 BaseMapper
@Repository //代表持久層
public interface UserMapper extends BaseMapper<User>{
List<User> selectList();
// 所有的CRUD都撰寫完成
//不用像以前那樣,撰寫CRUD以及組態檔
}
- 注意點:需要在主程式中添加@MapperScan(“com.kk.mapper”)
package com.kk;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//掃描我們的mapper檔案夾
@MapperScan("com.kk.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
- 測驗
package com.kk;
import com.kk.mapper.UserMapper;
import com.kk.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class MybatisPlusApplicationTests {
//繼承了BaseMapper BaseMapper所有的方法都可以被使用
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
//引數是一個mapper 條件構造器 這里不用
//查詢全部用戶
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
測驗成!

4、配置日志輸出
#配置日志輸出
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

5、插入測驗及雪花演算法
6、CRUD擴展
1、插入操作
//測驗插入功能
@Test
public void testInsert(){
User user = new User();
user.setName("kk");
user.setAge(17);
user.setEmail("30666@qq.com");
//這里需要一個User物件,所以需要new一個User
int result = userMapper.insert(user); //幫我們自動生成id
System.out.println(result);//受影響的函行數
System.out.println(user);//發現,id會自動回填
}

2、主鍵生成策略
默認 ID_WORKER全部唯一id
雪花演算法:
? snowflake是Twitter開源的分布式ID生成演算法,結果是一個long型的ID,其核心思想是:使用41bit作為毫秒數,10bit作為機器的ID(5個bit是資料中心,5個bit的機器ID),12bit作為毫秒內的流水號(意味著每個節點在每毫秒可以產生 4096 個 ID),最后還有一個符號位,永遠是0,具體實作的代碼可以參看https://github.com/twitter/snowflake,雪花演算法支持的TPS可以達到419萬左右(2^22*1000),
主鍵自增
配置主鍵自增:
1、物體類欄位上寫上@TableId(type = IdType.AUTO)
2、資料庫欄位一定要是自增!

其余原始碼解釋
public enum IdType {
AUTO(0),//資料庫ID自增
NONE(1),//該型別為未設定主鍵型別
INPUT(2),//用戶輸入ID
//該型別可以通過自己注冊自動填充插件進行填充
//以下3種型別、只有當插入物件ID 為空,才自動填充,
ID_WORKER(3),//全域唯一ID (idWorker)
UUID(4),//全域唯一ID (UUID)
ID_WORKER_STR(5);//字串全域唯一ID (idWorker 的字串表示)
}
測驗:
User物體類
package com.kk.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
//對應資料庫中的主鍵(uuid,自增id,雪花演算法,redis,zookeeper)
@TableId(type = IdType.INPUT) //一旦手動輸入id之后,就需要自己配置id
private Long id;
private String name;
private Integer age;
private String email;
}
測驗類:
package com.kk;
import com.kk.mapper.UserMapper;
import com.kk.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class MybatisPlusApplicationTests {
//繼承了BaseMapper BaseMapper所有的方法都可以被使用
@Autowired
private UserMapper userMapper;
//測驗插入功能
@Test
public void testInsert(){
User user = new User();
user.setId(6L);
user.setName("kk");
user.setAge(17);
user.setEmail("30666@qq.com");
//這里需要一個User物件,所以需要new一個User
int result = userMapper.insert(user); //幫我們自動生成id
System.out.println(result);//受影響的函行數
System.out.println(user);//發現,id會自動回填
}
}
3、更新操作
//測驗更新功能
@Test
public void testUpdate(){
User user = new User();
//通過調節自動拼接動態sql
user.setId(6L);
user.setName("kkkk");
user.setAge(999);
//updateById 其引數是一個物件
int i = userMapper.updateById(user);
System.out.println(i);
}
4、自動填充
==創建時間、修改時間!這些操作一遍都是自動化完成的,不用手動更新!
gmt_create:創建時間,gmt_modified:修改時間機會所有的表都需要配置,而且需要自動化
方式一:資料庫級別(作業中不建議使用)
1、在表中新增欄位 create_time,update_time

2、再次測驗插入方法
物體類中增加欄位
private Date createTime;
private Date updateTime;
測驗
//測驗更新功能
@Test
public void testUpdate(){
User user = new User();
//通過調節自動拼接動態sql
user.setId(6L);
user.setName("kkkk");
user.setAge(9999);
//updateById 其引數是一個物件
int i = userMapper.updateById(user);
System.out.println(i);
}

方式二:代碼級別
1、刪除資料庫的默認值、更新操作!

2、物體類的欄位屬性上需要增加注解
//記住用util包下的Date!!
//欄位添加填充內容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
3、撰寫處理器來處理這個注解
package com.kk.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component //一定要注意把處理器加到IOC容器中
public class MyMetaObjectHandler implements MetaObjectHandler {
//插入時候的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ... ...");
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
//更新時候的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("start insert fill ... ...");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
測驗
//測驗插入功能
@Test
public void testInsert(){
User user = new User();
// user.setId(6L);
user.setName("qq");
user.setAge(17);
user.setEmail("30666@qq.com");
//這里需要一個User物件,所以需要new一個User
int result = userMapper.insert(user); //幫我們自動生成id
System.out.println(result);//受影響的函行數
System.out.println(user);//發現,id會自動回填
}
//測驗更新功能
@Test
public void testUpdate(){
User user = new User();
//通過調節自動拼接動態sql
user.setId(1442085733983649796L);
user.setName("kkkk");
user.setAge(99999);
//updateById 其引數是一個物件
int i = userMapper.updateById(user);
System.out.println(i);
}

5、樂觀鎖
樂觀鎖:顧名思義,總是認為不會出現問題,無論干什么不去上鎖!如果出現了問題,再次更新值測驗
悲觀鎖:顧名思義,總是認為會出現問題,無論干什么都上鎖!再去操作!
樂觀鎖實作方式:
- 取出記錄時,獲取當前version
- 更新時,帶上這個version
- 執行更新時,set version = newVersion where version = oldVersion
- 如果version不對,就更新失敗
l樂觀鎖:1、先查詢,獲取版本號 version=1
--- A執行緒
update user set name="kk",version=version+1
where id=2 and version=1
--- B 執行緒 搶先完成 ,這個時候 version=2 會導致A修改失敗
update user set name="kk",version=version+1
where id=2 and version=1
測驗MP的樂觀鎖插件
1、給資料庫中增加version欄位

2、物體類增加對應的欄位
@Version //代表樂觀鎖的注解
private Integer version;
3、注冊組件
package com.kk.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//掃描我們的mapper檔案夾
@MapperScan("com.kk.mapper")
@EnableTransactionManagement
@Configuration //配置類 需要添加Configuration
public class MybatisConfig {
//注冊樂觀鎖插件
/**
* 舊版
*/
/* @Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}*/
/**
* 新版
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mybatisPlusInterceptor;
}
}
4、測驗
// 測驗樂觀鎖 ---成功
@Test
public void testmybatisPlusInterceptor(){
//1.查詢用戶資訊
User user = userMapper.selectById(1L);
//2.修改用戶資訊
user.setName("kk");
user.setEmail("0000@qq.com");
//3.執行更新操作
userMapper.updateById(user);
}
// 測驗樂觀鎖 ---失敗 多執行緒下
@Test
public void testmybatisPlusInterceptor2(){
//執行緒1
User user = userMapper.selectById(1L);
user.setName("kk111");
user.setEmail("0000@qq.com");
//模擬另外一個執行緒執行了插隊操作
User user2 = userMapper.selectById(1L);
user2.setName("kk222");
user2.setEmail("0000@qq.com");
userMapper.updateById(user2);
//可以使用自旋鎖來嘗試多次提交
userMapper.updateById(user); //如果沒有樂觀鎖就會覆寫插隊執行緒的值
}
7、查詢操作
//測驗查詢 (測驗批量查詢)
@Test
public void testSelectById(){
// User user = userMapper.selectById(1L);
List<User> users = userMapper.selectBatchIds(Arrays.asList(1,2,3));
users.forEach(System.out::println);
}
//條件查詢 map操作
@Test
public void testSelectByBatchIds(){
HashMap<String, Object> map = new HashMap<>();
//自定義要查詢到的條件
map.put("name","kk");
map.put("age","17");
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
8、分頁查詢
MbatisPlus內置了分頁插件
1、配置攔截器組件
// 舊版
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 設定請求的頁面大于最大頁后操作, true調回到首頁,false 繼續請求 默認false
// paginationInterceptor.setOverflow(false);
// 設定最大單頁限制數量,默認 500 條,-1 不受限制
// paginationInterceptor.setLimit(500);
// 開啟 count 的 join 優化,只針對部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
// 最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
2、直接使用Page物件即可
//測驗分頁查詢
@Test
public void testPage(){
//引數一 當前頁
//引數二 頁面大小
Page<User> page = new Page<>(1,5);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
}
9、洗掉操作
//測驗洗掉
@Test
public void testDeleteById(){
userMapper.deleteById(1442085733983649796L);
}
//批量通過洗掉
@Test
public void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1442085733983649794L,1442085733983649795L));
}
//通過map洗掉
@Test
public void testDeleteMap(){
HashMap<String,Object> map = new HashMap<>();
map.put("name","Tom");
userMapper.deleteByMap(map);
}
9、邏輯洗掉
物理洗掉:從資料庫中直接移除
邏輯洗掉: 在資料庫中沒有被移除,而是通過一個變數來讓他失效! deleted=0=>deleted=1
管理員可以查看被洗掉的記錄!防止資料的丟失,類似于回收站!
測驗:
1.在資料表中增加一個deleted欄位

2.物體類中增加屬性
//邏輯洗掉
@TableLogic
private Integer deleted;
3.配置(現在新版的Mybatis不用下面的這個方法)
config
//注冊邏輯洗掉
@Bean
public ISqlInjector sqlInjector(){
return new LogicSqlInjector();
}
application.properties
# 配置邏輯洗掉組件
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
其實執行的時update

10.性能分析插件
作用:性能分析攔截器,用于輸入每天SQL陳述句及其執行時間
MybatisPlus提供了性能分析插件,如果超過這個時間就停止運行!
1、匯入插件
/**
* SQL執行效率插件
*/
@Bean
@Profile({"dev","test"})// 設定 dev test 環境開啟,保證我們的效率
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(100); //ms 設定sql執行的最大時間,如果超過了則不執行
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
2、配置
# 設定開發環境
spring.profiles.active=dev
3、測驗
//測驗分頁查詢
@Test
public void testPage(){
//引數一 當前頁
//引數二 頁面大小
Page<User> page = new Page<>(1,5);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
}
11、條件查詢器Wrapper
一些復雜的sql就可以用wrapper代替

1、測驗一:
package com.kk;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kk.mapper.UserMapper;
import com.kk.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class WrapperTest {
//繼承了BaseMapper BaseMapper所有的方法都可以被使用
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
//查詢name不為空的用戶,并且郵箱不為空的用戶,年齡大于等于18歲
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age",18);
userMapper.selectList(wrapper).forEach(System.out::println);
}
}
2、測驗二
@Test
void test2(){
//查詢名字等于zz的
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","小白");
User user = userMapper.selectOne(wrapper); //查詢一個資料
// 如果有出現多個資料結果,使用list或者Map
System.out.println(user);
}
注意:deleted=1的是查不出來的

3、測驗三
@Test
void test3(){
//查詢年齡在 18-35之間的用戶
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,35);
Long count = userMapper.selectCount(wrapper);//查詢結果數
System.out.println(count);
}

?
4、測驗四
//模糊查詢
@Test
void test4(){
//查詢年齡在 18-35之間的用戶
QueryWrapper<User> wrapper = new QueryWrapper<>();
//左和右 e%(在右) %e(在左)
wrapper
.notLike("name","e")
.likeRight("email","t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}

5、測驗五
@Test
void test5(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
//id 在子查詢中查出來
wrapper.inSql("id","select id from user where id <3");
List<Object> objects = userMapper.selectObjs(wrapper);
objects.forEach(System.out::println);
}

6、測驗六
//查詢排序
@Test
void test6(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
//通過id進行排序
wrapper.orderByDesc("id");
//Desc 降序
//Asc 升序
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}

12、代碼生成器
? AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個模塊的代碼,極大的提升了開發效率,
匯入所有的依賴
<dependencies>
<!-- 模板引擎 velocity-engine-core-->
<!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity-engine-core -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<!-- 資料庫驅動 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<!-- mybatis-plus -->
<!-- mybatis-plus 是自己開發,并非官方的! -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
注意:如果引擎包和這個lang3的依賴包匯入不了,需要在該專案建立lib檔案夾,并將這兩個包匯入,并且添加為庫

測驗:
package com.kk;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
//代碼自動生成器
public class KkCode {
public static void main(String[] args) {
// 需要構建一個 代碼自動生成器 物件
AutoGenerator mpg = new AutoGenerator();
// 配置策略
// 1、全域配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("kk"); gc.setOpen(false);
gc.setFileOverride(false);
// 是否覆寫
gc.setServiceName("%sService");
// 去Service的I前綴
gc.setIdType(IdType.ID_WORKER);
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
//2、設定資料源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis-plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc);
//3、包的配置
PackageConfig pc = new PackageConfig();
//只需要改物體類名字 和包名 還有 資料庫配置即可
pc.setModuleName("blog");
pc.setParent("com.kk");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
//4、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user");
// 設定要映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
// 自動lombok;
strategy.setLogicDeleteFieldName("deleted");
// 自動填充配置
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate); tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
// 樂觀鎖
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
// localhost:8080/hello_id_2
mpg.setStrategy(strategy);
mpg.execute(); //執行
}
}
測驗成功!
troller");
mpg.setPackageInfo(pc);
//4、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user");
// 設定要映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
// 自動lombok;
strategy.setLogicDeleteFieldName("deleted");
// 自動填充配置
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate); tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
// 樂觀鎖
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
// localhost:8080/hello_id_2
mpg.setStrategy(strategy);
mpg.execute(); //執行
}
}
==測驗成功!==

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/305442.html
標籤:java
