【SpringBoot探索五】SpringBoot專案整合Mybatis框架之使用Mybatis Plus外掛
阿新 • • 發佈:2019-01-04
Mybatis Plus是一款非常優秀的Mybatis擴充套件外掛,該開源專案是由國人發起的。使用該外掛可以簡化我們的開發,它有很多優良的特性,比如通用CRUD操作,支援ActiveRecord,內建分頁外掛等等。
1.新增pom依賴
<!--mybatis plus會維護mybatis依賴,去除該依賴-->
<!--<dependency>-->
<!--<groupId>org.mybatis.spring.boot</groupId>-->
<!--<artifactId>mybatis-spring-boot-starter</artifactId>-->
<!--<version>1.3.0</version>-->
<!--</dependency>-->
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version >2.1.9</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>1.0.5</version>
</dependency>
2.配置檔案中配置mybatis plus屬性
mybatis-plus :
mapper-locations: classpath:/mapper/*.xml
#實體掃描,多個package用逗號或者分號分隔
typeAliasesPackage: com.my.webapp.dao.entity
#typeEnumsPackage: com.baomidou.springboot.entity.enums
global-config:
#主鍵型別 0:"資料庫ID自增", 1:"使用者輸入ID",2:"全域性唯一ID (數字型別唯一ID)", 3:"全域性唯一ID UUID";
id-type: 1
#欄位策略 0:"忽略判斷",1:"非 NULL 判斷"),2:"非空判斷"
field-strategy: 1
#駝峰下劃線轉換
db-column-underline: true
#重新整理mapper 除錯神器
refresh-mapper: true
#資料庫大寫下劃線轉換
#capital-mode: true
#序列介面實現類配置
#key-generator: com.baomidou.springboot.xxx
#邏輯刪除配置(下面3個配置)
logic-delete-value: 0
logic-not-delete-value: 1
sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
#自定義填充策略介面實現
#meta-object-handler: com.baomidou.springboot.xxx
#自定義SQL注入器
#sql-injector: com.baomidou.springboot.xxx
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
3.建立實體類和Mapper
先建立一張測試表
create table t_wa_user
(
id bigint auto_increment
primary key,
user_name varchar(45) not null comment '使用者名稱',
password varchar(45) not null comment '密碼'
)
comment '使用者表'
;
建立實體類
User.java
package com.my.webapp.dao.entity;
import com.baomidou.mybatisplus.annotations.TableName;
/**
*/
//不指定表名預設為user表
@TableName("t_wa_user")
public class User {
private Long id;
/**
* 使用者名稱
*/
private String userName;
/**
* 密碼
*/
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
建立Mapper,繼承mybatis plus包下的BaseMapper介面
UserMapper.java
package com.my.webapp.dao.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.my.webapp.dao.entity.User;
/**
*/
public interface UserMapper extends BaseMapper<User> {
}
BaseMapper介面中為我們提供了常用的CRUD操作,我們甚至不需要建立xml檔案就可以在程式碼中直接使用
如:
進行分頁查詢
private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());
@Autowired
private UserMapper userMapper;
@Test
public void queryTest() {
User user = new User();
user.setUserName("測試");
user.setPassword("123456");
userMapper.insert(user);
List<User> users = userMapper.selectPage(new Page<User>(1,2), new EntityWrapper<User>().eq("user_name", "測試"));
logger.debug("size: "+users.size());
}
當然較複雜或使用頻率高的sql還是推薦寫在xml檔案中
4.ActiveRecord模式進行CRUD操作
實體類需要繼承Model類
User.java
package com.my.webapp.dao.entity;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
/**
*/
@TableName("t_wa_user")
public class User extends Model<User>{
private Long id;
/**
* 使用者名稱
*/
private String userName;
/**
* 密碼
*/
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
//指定主鍵
@Override
protected Serializable pkVal() {
return this.id;
}
}
然後這樣:
@Test
public void insertTest() {
User user = new User();
user.setUserName("測試");
user.setPassword("3243");
user.insert();
}
相信您現在應該已經感受到了mybatis plus的魅力了。
5.使用程式碼生成器
如果我們需要通過mybatis plus生成實體類,Mapper,xml等。則需要使用程式碼生成器
1>.新增依賴
<!-- 模板引擎 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<!-- 模板引擎,需要指定 mpg.setTemplateEngine(new FreemarkerTemplateEngine()); -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.27-incubating</version>
</dependency>
2>.配置生成引數
MpGenerator.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
/**
* <p>
* 程式碼生成器演示
* </p>
*/
public class MpGenerator {
/**
* <p>
* MySQL 生成演示
* </p>
*/
public static void generate(GeneratorParam param){
AutoGenerator mpg = new AutoGenerator();
// 選擇 freemarker 引擎,預設 Veloctiy
// mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 全域性配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(param.getPath());
gc.setFileOverride(true);
gc.setActiveRecord(true);// 不需要ActiveRecord特性的請改為false
gc.setEnableCache(false);// XML 二級快取
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
//gc.setKotlin(true); //是否生成 kotlin 程式碼
gc.setAuthor(param.getAuthor());
// 自定義檔案命名,注意 %s 會自動填充表實體屬性!
// gc.setMapperName("%sDao");
// gc.setXmlName("%sDao");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
mpg.setGlobalConfig(gc);
// 資料來源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert(){
// 自定義資料庫表字段型別轉換【可選】
@Override
public DbColumnType processTypeConvert(String fieldType) {
System.out.println("轉換型別:" + fieldType);
// 注意!!processTypeConvert 存在預設型別轉換,如果不是你要的效果請自定義返回、非如下直接返回。
return super.processTypeConvert(fieldType);
}
});
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername(param.getUserName());
dsc.setPassword(param.getPassword());
dsc.setUrl(param.getUrl());
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// strategy.setCapitalMode(true);// 全域性大寫命名 ORACLE 注意
strategy.setTablePrefix(new String[] { "t_wa_"});// 此處可以修改為您的表字首
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(new String[] { param.getTableName() }); // 需要生成的表
// strategy.setExclude(new String[]{"test"}); // 排除生成的表
// 自定義實體父類
// strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
// 自定義實體,公共欄位
// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
// 自定義 mapper 父類
// strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
// 自定義 service 父類
// strategy.setSuperServiceClass("com.baomidou.demo.TestService");
// 自定義 service 實現類父類
// strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
// 自定義 controller 父類
// strategy.setSuperControllerClass("com.baomidou.demo.TestController");
// 【實體】是否生成欄位常量(預設 false)
// public static final String ID = "test_id";
// strategy.setEntityColumnConstant(true);
// 【實體】是否為構建者模型(預設 false)
// public User setName(String name) {this.name = name; return this;}
// strategy.setEntityBuilderModel(true);
strategy.setDbColumnUnderline(true);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.my.webapp");
pc.setModuleName("dao");
mpg.setPackageInfo(pc);
// 注入自定義配置,可以在 VM 中使用 cfg.abc 【可無】
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
this.setMap(map);
}
};
// 自定義 xxList.jsp 生成
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
focList.add(new FileOutConfig("/template/list.jsp.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸入檔名稱
return "D://my_" + tableInfo.getEntityName() + ".jsp";
}
});
cfg.setFileOutConfigList(focList);
//mpg.setCfg(cfg);
// 調整 xml 生成目錄演示
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return param.getPath() + tableInfo.getEntityName() +"Mapper" + ".xml";
}
});
cfg.setFileOutConfigList(focList);
//mpg.setCfg(cfg);
// 關閉預設 xml 生成,調整生成 至 根目錄
//TemplateConfig tc = new TemplateConfig();
//tc.setXml(null);
//mpg.setTemplate(tc);
// 自定義模板配置,可以 copy 原始碼 mybatis-plus/src/main/resources/templates 下面內容修改,
// 放置自己專案的 src/main/resources/templates 目錄下, 預設名稱一下可以不配置,也可以自定義模板名稱
// TemplateConfig tc = new TemplateConfig();
// tc.setController("...");
// tc.setEntity("...");
// tc.setMapper("...");
// tc.setXml("...");
// tc.setService("...");
// tc.setServiceImpl("...");
// 如上任何一個模組如果設定 空 OR Null 將不生成該模組。
// mpg.setTemplate(tc);
// 執行生成
mpg.execute();
// 列印注入設定【可無】
// System.err.println(mpg.getCfg().getMap().get("abc"));
}
public static void main(String[] args) {
GeneratorParam param = new GeneratorParam();
param.setUrl("jdbc:mysql://127.0.0.1:3306/web_app?useUnicode=true&characterEncoding=UTF-8&useSSL=false")
.setUserName("root")
.setTableName("t_wa_sign_record")
.setPath("E://java/")
.setPassword("")
.setAuthor("struggling_rong");
generate(param);
}
}
GeneratorParam.java
/**
*/
public class GeneratorParam {
/**
* 存放檔案的路徑
*/
private String path;
/**
* 表名
*/
private String tableName;
private String userName;
private String password;
private String url;
private String author;
public String getAuthor() {
return author;
}
public GeneratorParam setAuthor(String author) {
this.author = author;
return this;
}
public String getUserName() {
return userName;
}
public GeneratorParam setUserName(String userName) {
this.userName = userName;
return this;
}
public String getPassword() {
return password;
}
public GeneratorParam setPassword(String password) {
this.password = password;
return this;
}
public String getUrl() {
return url;
}
public GeneratorParam setUrl(String url) {
this.url = url;
return this;
}
public String getPath() {
return path;
}
public GeneratorParam setPath(String path) {
this.path = path;
return this;
}
public String getTableName() {
return tableName;
}
public GeneratorParam setTableName(String tableName) {
this.tableName = tableName;
return this;
}
}
執行main方法後,E:\java目錄下則生成了我們想要的檔案。