歐幾里得 歐幾里得擴充套件 尤拉函式 C++模板
技術標籤:mybatis
一、快速入門
1.1 簡介
MyBatis-Plus (簡稱 MP)是一個 MyBatis (opens new window)的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。
特性
- 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
- 損耗小:啟動即會自動注入基本 CURD,效能基本無損耗,直接面向物件操作
- 強大的 CRUD 操作:內建通用 Mapper、通用 Service,僅僅通過少量配置即可實現單表大部分 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 操作智慧分析阻斷,也可自定義攔截規則,預防誤操作
1.2框架結構
1.3 快速入門
- 建立資料表
CREATE DATABASE mybatisPlus;
USE mybatisPlus;
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)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
- 初始化工程
建立一個空的 Spring Boot 工程
- 匯入依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 配置
在 application.properties
配置檔案中新增 資料庫的相關配置:
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/mybatisPlus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
在 Spring Boot 啟動類中新增 @MapperScan
註解,掃描 Mapper 資料夾:
@SpringBootApplication
@MapperScan("com.mybatisPlus.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- 編碼
編寫實體類 User.java
(此處使用了 Lombok (opens new window)簡化程式碼)
@Data
public class User {
private Long id;
private String name;
private int age;
private String email;
}
編寫Mapper類 UserMapper.java
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
- 測試
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
Assert.assertEquals(5, userList.size());
userList.forEach(System.out::println);
}
- 結果
二、CURD
2.1 配置日誌
#日誌配置
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
日誌輸出
2.2 插入操作
2.2.1 插入測試
- 插入使用者
@Test
public void insertTest(){
User user = new User();
user.setName("user");
user.setAge(12);
user.setEmail("[email protected]");
int insert=userMapper.insert(user);
System.out.println("insert = "+insert);
System.out.println(user);
}
- 插入結果
使用 雪花演算法 自動生成Id。
雪花演算法
snowflake是Twitter開源的分散式ID生成演算法,結果是一個long型的ID。其核心思想是:使用41bit作為毫秒數,10bit作為機器的ID(5個bit是資料中心,5個bit的機器ID),12bit作為毫秒內的流水號(意味著每個節點在每毫秒可以產生 4096 個 ID),最後還有一個符號位,永遠是0。具體實現的程式碼可以參看https://github.com/twitter/snowflake。
2.2.2 主鍵生成策略
public enum IdType {
AUTO, //資料庫自增
NONE, //不設定主鍵
INPUT, //手動輸入主鍵
ID_WORKER, //預設全域性唯一id
UUID, //全域性唯一id uuid
ID_WORKER_STR;//ID_WORKER的字串表示
private int key;
private IdType(int key) { /* compiled code */ }
public int getKey() { /* compiled code */ }
}
預設主鍵策略
//預設ID_WORKER 全域性唯一識別符號
@TableId(type = IdType.ID_WORKER)
private Long id;
主鍵自增
- 實體類欄位增加註釋
@TableId(type = IdType.AUTO)
private Long id;
- 資料庫欄位設定為自增
2.3 更新操作
2.3.1 自動填充
原理:
- 實現元物件處理器介面:com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
- 註解填充欄位
@TableField(.. fill = FieldFill.INSERT)
生成器策略部分也可以配置!
- 資料庫增加欄位
create_time
和update_time
- 實體類增加屬性
public class User {
...
//欄位新增填充內容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill=FieldFill.INSERT_UPDATE)
private Date updateTime;
}
-
實現元物件處理器介面
註釋
@Component
註冊為元件
@Slf4j
@Component
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 update fill");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
-
啟動類掃描
掃描配置類
MyMetaObjectHandler
@SpringBootApplication
@MapperScan("com.mybatisPlus.mapper")
@ComponentScan("com.mybatisPlus.handler")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.3.2 更新測試
- 測試更新
@Test
public void updateTest(){
User user = new User();
user.setId(1L);
user.setName("Billie");
user.setAge(25);
int update = userMapper.updateById(user);
}
- 測試結果
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-4RCYGzyW-1610295243976)(C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20210107204955804.png)]
2.4 樂觀鎖
當要更新一條記錄的時候,希望這條記錄沒有被別人更新
樂觀鎖實現方式:
- 取出記錄時,獲取當前version
- 更新時,帶上這個version
- 執行更新時, set version = newVersion where version = oldVersion
- 如果version不對,就更新失敗
2.4.1 實現樂觀鎖
- 資料表增加
version
欄位
ALTER TABLE `mybatisplus`.`user`
ADD COLUMN `version` INT NULL DEFAULT 1 AFTER `update_time`;
- 實體類增加屬性
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
...
@Version
private Integer version;
...
}
- 配置攔截器
MybatisPlusConfig.java
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
-
啟動類掃描
掃描配置類MybatisPlusConfig
@SpringBootApplication
@MapperScan("com.mybatisPlus.mapper")
@ComponentScan("com.mybatisPlus.handler")
@ComponentScan("com.mybatisPlus.config")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.4.2 測試樂觀鎖
- 測試程式碼
@Test
public void optimisticLockerTest(){
User user = userMapper.selectById(1L);
user.setName("user0");
userMapper.updateById(user);
}
-
測試結果
version
自動加1
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-IJotL0lt-1610295243978)(C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20210110142252818.png)]
2.5 查詢操作
2.5.1 普通查詢
- 根據
id
查詢selectById
@Test
public void selectByIdTest(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
- 批量查詢
selectBatchIds
@Test
public void selectBatchIdsTest(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1L,2L,3L));
users.forEach(System.out::println);
}
- Map集合查詢
selectByMap
@Test
public void selectByMapTest(){
Map<String,Object> map=new HashMap<>();
map.put("name","jack");
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
2.5.2 分頁查詢
- 配置攔截器
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//樂觀鎖配置
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
//分頁配置
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
- 分頁測試
@Test
public void selectByPage(){
Page<User> page=new Page<>(0,3);
userMapper.selectPage(page, null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());
}
2.6 刪除操作
2.6.1 普通刪除
- 根據
id
刪除deleteById
@Test
public void deleteByIdTest(){
int deleted = userMapper.deleteById(1L);
System.out.println(deleted);
}
- 批量刪除
deleteBatchIds
@Test
public void deleteBatchIdsTest(){
int deleted = userMapper.deleteBatchIds(Arrays.asList(2L,3L));
System.out.println(deleted);
}
- Map集合刪除
deleteByMap
@Test
public void deleteByMapTest(){
Map<String,Object> map=new HashMap<>();
map.put("name","jack");
int deleted = userMapper.deleteByMap(map);
System.out.println(deleted);
}
2.6.2 邏輯刪除
- 資料表增加
deleted
欄位
ALTER TABLE `mybatisplus`.`user`
ADD COLUMN `deleted` INT(1) NULL DEFAULT 0 AFTER `update_time`;
- 實體類增加屬性
deleted
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
...
@TableLogic
private int deleted;
}
- 配置邏輯刪除
application.properties
#配置邏輯刪除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
4.測試邏輯刪除
@Test
public void logicDeleteTest(){
userMapper.deleteById(4L);
}
- 邏輯刪除結果
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-vVV6x5N7-1610295243982)(C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20210110150433767.png)]
三、執行 SQL 分析列印
該功能依賴 p6spy
元件,完美的輸出列印 SQL 及執行時長。
p6Spy通過劫持JDBC驅動,在呼叫實際JDBC
驅動前攔截呼叫的目標語,達到SQL
語句日誌記錄的目的。它包括P6Log
和P6Outage
兩個模組。
P6Log 用來攔截和記錄任務應用程式的 JDBC 語句;P6Outage 專門用來檢測和記錄超過配置條件裡時間的 SQL 語句。
1.匯入依賴
<!-- 控制檯 SQL日誌列印外掛 -->
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.8.1</version>
</dependency>
2.修改資料庫連線`application.properties`
#資料庫連線配置
spring.datasource.username=root
spring.datasource.password=root
#spring.datasource.url=jdbc:mysql://localhost:3306/mybatisPlus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/mybatisPlus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
#日誌配置
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#配置邏輯刪除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
3.p6spy配置spy.properties
#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定義日誌列印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日誌輸出到控制檯
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日誌系統記錄 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 設定 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL字首
useprefix=true
# 配置記錄 Log 例外,可去掉的結果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 實際驅動可多個
#driverlist=org.h2.Driver
# 是否開啟慢SQL記錄
outagedetection=true
# 慢SQL記錄標準 2 秒
outagedetectioninterval=2
- 實現
MessageFormattingStrategy
介面,編寫sql輸出格式化
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class P6spySqlFormatConfig implements MessageFormattingStrategy {
//sql格式化輸出
@Override
public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) {
return !"".equals(sql.trim())
?
"[ " + LocalDateTime.now() + " ] --- | took " + elapsed + "ms | " + prepared + "|" + category + " | connection " + connectionId + "\n "
+ sql + ";"
: "";
}
//日期格式化
public String formatFullTime(LocalDateTime localDateTime, String pattern) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
return localDateTime.format(dateTimeFormatter);
}
}
- 測試
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
}
- 結果分析
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-ufU6bJFW-1610295243986)(C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20210111001203317.png)]
四、條件查詢其Wrapper
- ge & isNotNull
ge:大於等於 >=
例:
ge("age", 18)
—>age >= 18
isNotNull:欄位 IS NOT NULL
例:
isNotNull("name")
—>name is not null
測試程式碼
@Test
public void test() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age", 12);
userMapper.selectList(wrapper).forEach(System.out::println);
}
執行SQL
SELECT id,name,age,email,version,create_time,update_time,deleted FROM user WHERE deleted=0 AND (name IS NOT NULL AND email IS NOT NULL AND age >= ?)
- eq
eq:等於 =
例:
eq("name", "老王")
—>name = '老王'
測試程式碼
@Test
public void test() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","sandy");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
執行SQL
SELECT id,name,age,email,version,create_time,update_time,deleted FROM user WHERE deleted=0 AND (name = ?)
- between
between:BETWEEN 值1 AND 值2
例:
between("age", 18, 30)
—>age between 18 and 30
測試程式碼
@Test
public void test(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,24); // 區間
Integer count = userMapper.selectCount(wrapper);// 查詢結果數
System.out.println(count);
}
執行SQL
SELECT COUNT( 1 ) FROM user WHERE deleted=0 AND (age BETWEEN ? AND ?)
- notLike
notLike:NOT LIKE ‘%值%’
例:
notLike("name", "王")
—>name not like '%王%'
likeRight:LIKE ‘值%’
例:
likeRight("name", "王")
—>name like '王%'
測試程式碼
@Test
public void test(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.notLike("name","e")
.likeRight("email","t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}
執行SQL
SELECT id,name,age,email,version,create_time,update_time,deleted FROM user WHERE deleted=0 AND (name NOT LIKE ? AND email LIKE ?)
- inSql
inSql:欄位 IN ( sql語句 )
例:
inSql("age", "1,2,3,4,5,6")
—>age in (1,2,3,4,5,6)
例:
inSql("id", "select id from table where id < 3")
—>id in (select id from table where id < 3)
測試程式碼
@Test
public void test(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.inSql("id","select id from user where id<5");
List<Object> objects = userMapper.selectObjs(wrapper);
objects.forEach(System.out::println);
}
執行SQL
SELECT id,name,age,email,version,create_time,update_time,deleted FROM user WHERE deleted=0 AND (id IN (select id from user where id<5))
- orderByAsc & orderByDesc
orderByAsc :升序排列:ORDER BY 欄位, … ASC
例:
orderByAsc("id", "name")
—>order by id ASC,name ASC
orderByDesc:降序排序:ORDER BY 欄位, … DESC
例:
orderByDesc("id", "name")
—>order by id DESC,name DESC
測試程式碼
@Test
public void test(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.orderByAsc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
執行SQL
SELECT id,name,age,email,version,create_time,update_time,deleted FROM user WHERE deleted=0 ORDER BY id ASC
五、程式碼自動生成器
1.建立資料表
DROP TABLE IF EXISTS blog;
CREATE TABLE blog
(
id BIGINT(20) NOT NULL COMMENT '部落格主鍵ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '部落格名字',
content VARCHAR(50) NULL DEFAULT NULL COMMENT '部落格內容',
version INT(11) NULL DEFAULT NULL COMMENT '樂觀鎖',
create_time DATETIME NULL DEFAULT NULL COMMENT '建立時間',
update_time DATETIME NULL DEFAULT NULL COMMENT '修改時間',
deleted INT(1) NULL DEFAULT 0 COMMENT '邏輯刪除',
PRIMARY KEY (id)
);
- 匯入依賴
<!--新增 程式碼生成器 依賴-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!--新增 模板引擎 依賴-->
<!--MyBatis-Plus 支援 Velocity(預設)、Freemarker、Beetl,使用者可以選擇自己熟悉的模板引擎.-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
-
程式碼生成器
CodeGenerator.java
通過
strategy.setInclude("tableName")
設定要對映的表名
package com.mybatisPlus.demo;
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 com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
public class CodeGenerator {
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("baoZhou");
gc.setOpen(false);
gc.setFileOverride(false); // 是否覆蓋
gc.setServiceName("%sService"); // 去Service的I字首
gc.setIdType(IdType.ID_WORKER);
gc.setDateType(DateType.ONLY_DATE);
mpg.setGlobalConfig(gc);
//2、設定資料來源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatisPlus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
//3、包的配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("blog");
pc.setParent("com.mybatisPlus");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
//4、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("blog"); // 設定要對映的表名
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true); // 自動lombok;
strategy.setLogicDeleteFieldName("deleted");//設定邏輯刪除
// 5、自動填充配置
TableFill create_time = new TableFill("create_time", FieldFill.INSERT);
TableFill update_time = new TableFill("update_time", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(create_time);
tableFills.add(update_time);
strategy.setTableFillList(tableFills);
// 樂觀鎖
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
// set freemarker engine
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute(); //執行
}
}
- 生成結果
y.setLogicDeleteFieldName(“deleted”);//設定邏輯刪除
// 5、自動填充配置
TableFill create_time = new TableFill(“create_time”, FieldFill.INSERT);
TableFill update_time = new TableFill(“update_time”, FieldFill.INSERT_UPDATE);
ArrayList tableFills = new ArrayList<>();
tableFills.add(create_time);
tableFills.add(update_time);
strategy.setTableFillList(tableFills);
// 樂觀鎖
strategy.setVersionFieldName(“version”);
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
// set freemarker engine
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute(); //執行
}
}
4. 生成結果
<img src="C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20210110232703621.png" alt="image-20210110232703621" style="zoom:80%;" />