一、前言
- 業務繁重了,項目多了;總想"偷懶" 罒ω罒,利用自動化工具提高工作效率;這樣,就可以騰出時間(#^.^#),學習總結,提高設計能力,搞些"高大上"的架構 (#^.^#)。
- 你要上新技術、運用新框架,記得一定要準從組織戰略方針指導意見,統一技術棧。技術職位越高,越要從多方面(維護成本、組員學習成本、時間成本、影響風險)謹慎選擇,考慮周全。
- 相中了mybatis plus以下特性(引用官方):
- 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
- 損耗小:啓動即會自動注入基本 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 操作智能分析阻斷,也可自定義攔截規則,預防誤操作
二、配置
- 以下配置只是集成配置,並不能保證每個項目都通用,要學會因地制宜。
- maven依賴(如果老項目引用,一定要將原版mybatis與spring boot集成jar包註釋了,mybatis-spring-boot-starter)
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.1</version>
<exclusions>
<exclusion>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- properties
## pojo所在包,使用該註解,在mapper.xml中將不必使用pojo全名-替換
mybatis-plus.type-aliases-package=com.exam.fast.data.dao.po
## mapper.xml所在路徑-替換
mybatis-plus.mapper-locations=classpath*:/mapper/**/*Mapper.xml
mybatis-plus.config-location=classpath:myBatis-config.xml
- 分頁配置類
/**
* @desc: mybatis plus分頁插件
* @author: yanfei
* @date: 2019/10/28
*/
@EnableTransactionManagement
@Configuration
@MapperScan("com.exam.fast.data.dao.mapper")
public class MybatisPlusConfig {
/**
* 邏輯刪除配置
* @return
*/
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 設置請求的頁面大於最大頁後操作, true調回到首頁,false 繼續請求 默認false
// paginationInterceptor.setOverflow(false);
// 設置最大單頁限制數量,默認 500 條,-1 不受限制
// paginationInterceptor.setLimit(500);
List<ISqlParser> sqlParserList = new ArrayList<>();
// 攻擊 SQL 阻斷解析器、加入解析鏈
sqlParserList.add(new BlockAttackSqlParser() {
@Override
public void processDelete(Delete delete) {
// 如果你想自定義做點什麼,可以重寫父類方法像這樣子
// 自定義跳過某個表,其他關聯表可以調用 delete.getTables() 判斷
super.processDelete(delete);
}
});
paginationInterceptor.setSqlParserList(sqlParserList);
return paginationInterceptor;
}
}
三、自動生成
- generator-config.properties
#非mapper xml文件生成路徑
outputDir=F:/demoSpace/dynamic-boot/src/main/java
#mapper xml文件生成路徑
outputXmlDir=F:/demoSpace/dynamic-boot/src/main/resources
#父包名路徑;
package.parent=com.exam.fast
#數據庫配置
ds.driver-class-name=com.mysql.jdbc.Driver
ds.username=root
ds.password=yanfei010203
ds.url=jdbc:mysql://192.168.11.138:3306/test?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
- CodeGenerator
/**
* @desc: 執行 main 方法控制檯輸入模塊表名回車自動生成對應項目目錄中
* @author: yanfei
* @date: 2019/10/25
*/
public class CodeGenerator {
public static void main(String[] args) {
codeGenerator();
}
/**
* <p>
* 讀取控制檯內容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("請輸入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("請輸入正確的" + tip + "!");
}
/**
* 生成代碼配置
*/
public static void codeGenerator() {
String javaPath = PropKit.use("generator-config.properties").get("outputDir");
String xmlPath = PropKit.use("generator-config.properties").get("outputXmlDir");
String parentPath = PropKit.use("generator-config.properties").get("package.parent");
String driverName = PropKit.use("generator-config.properties").get("ds.driver-class-name");
String username = PropKit.use("generator-config.properties").get("ds.username");
String password = PropKit.use("generator-config.properties").get("ds.password");
String url = PropKit.use("generator-config.properties").get("ds.url");
// 代碼生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(javaPath);
gc.setAuthor("yanfei");
gc.setOpen(false);
// gc.setSwagger2(true); //實體屬性 Swagger2 註解
//例如:%sBusiness 生成 UserBusiness
gc.setServiceName("I%sManager");
//例如:%sBusinessImpl 生成 UserBusinessImpl
gc.setServiceImplName("%sManagerImpl");
gc.setBaseColumnList(true);
gc.setBaseResultMap(true);
mpg.setGlobalConfig(gc);
// 數據源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(url);
// dsc.setSchemaName("public");
dsc.setDriverName(driverName);
dsc.setUsername(username);
dsc.setPassword(password);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模塊名"));
pc.setParent(parentPath);
pc.setService("manager");
pc.setServiceImpl("manager.impl");
pc.setEntity("po");
mpg.setPackageInfo(pc);
// 自定義配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
// String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
String templatePath = "/templates/mapper.xml.vm";
// 自定義輸出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定義配置會被優先輸出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸出文件名 , 如果你 Entity 設置了前後綴、此處注意 xml 的名稱會跟着發生變化!!
return xmlPath + "/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判斷自定義文件夾是否需要創建
checkDir("調用默認方法創建的目錄");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板(默認自帶模板)
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定義輸出模板
//指定自定義模板路徑,注意不要帶上.ftl/.vm, 會根據使用的模板引擎自動識別
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//自定義基礎的Entity類
// strategy.setSuperEntityClass("com.exam.business.middle.fastboot.common.BaseEntity");
//是否爲lombok模型
strategy.setEntityLombokModel(true);
//生成 @RestController 控制器
strategy.setRestControllerStyle(true);
//自定義繼承的Controller類全稱,帶包名
// strategy.setSuperControllerClass("com.exam.business.middle.fastboot.common.BaseController");
// 寫於父類中的公共字段
// strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
//駝峯轉連字符
strategy.setControllerMappingHyphenStyle(true);
//是否生成實體時,生成字段註解
// strategy.setEntityTableFieldAnnotationEnable(true);
// strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new VelocityTemplateEngine());
mpg.execute();
}
}
- PropKit 工具類 (好用至極 O(∩_∩)O哈哈~)
/**
* desc:獲取文件工具類,可以在任何地方使用PropKit.Use("aa.txt").get("key")
* @author:yanfei
* date:2018/6/13
*/
public class PropKit {
private static Prop prop = null;
private static final ConcurrentHashMap<String, Prop> map = new ConcurrentHashMap<String, Prop>();
private PropKit() {
}
/**
* Using the properties file. It will loading the properties file if not loading.
*
* @see #use(String, String)
*/
public static Prop use(String fileName) {
return use(fileName, Prop.DEFAULT_ENCODING);
}
/**
* Using the properties file. It will loading the properties file if not loading.
* <p>
* Example:<br>
* PropKit.use("config.txt", "UTF-8");<br>
* PropKit.use("other_config.txt", "UTF-8");<br>
* <br>
* String userName = PropKit.get("userName");<br>
* String password = PropKit.get("password");<br>
* <br>
* userName = PropKit.use("other_config.txt").get("userName");<br>
* password = PropKit.use("other_config.txt").get("password");<br>
* <br>
* PropKit.use("com/cc/config_in_sub_directory_of_classpath.txt");
*
* @param fileName the properties file's name in classpath or the sub directory of classpath
* @param encoding the encoding
*/
public static Prop use(String fileName, String encoding) {
Prop result = map.get(fileName);
if (result == null) {
result = new Prop(fileName, encoding);
map.put(fileName, result);
if (PropKit.prop == null) {
PropKit.prop = result;
}
}
return result;
}
/**
* Using the properties file bye File object. It will loading the properties file if not
* loading.
*
* @see #use(File, String)
*/
public static Prop use(File file) {
return use(file, Prop.DEFAULT_ENCODING);
}
/**
* Using the properties file bye File object. It will loading the properties file if not
* loading.
* <p>
* Example:<br>
* PropKit.use(new File("/var/config/my_config.txt"), "UTF-8");<br>
* Strig userName = PropKit.use("my_config.txt").get("userName");
*
* @param file the properties File object
* @param encoding the encoding
*/
public static Prop use(File file, String encoding) {
Prop result = map.get(file.getName());
if (result == null) {
result = new Prop(file, encoding);
map.put(file.getName(), result);
if (PropKit.prop == null) {
PropKit.prop = result;
}
}
return result;
}
public static Prop useless(String fileName) {
Prop previous = map.remove(fileName);
if (PropKit.prop == previous) {
PropKit.prop = null;
}
return previous;
}
public static void clear() {
prop = null;
map.clear();
}
public static Prop getProp() {
if (prop == null) {
throw new IllegalStateException(
"Load propties file by invoking PropKit.use(String fileName) method first.");
}
return prop;
}
public static Prop getProp(String fileName) {
return map.get(fileName);
}
public static String get(String key) {
return getProp().get(key);
}
public static String get(String key, String defaultValue) {
return getProp().get(key, defaultValue);
}
public static Integer getInt(String key) {
return getProp().getInt(key);
}
public static Integer getInt(String key, Integer defaultValue) {
return getProp().getInt(key, defaultValue);
}
public static Long getLong(String key) {
return getProp().getLong(key);
}
public static Long getLong(String key, Long defaultValue) {
return getProp().getLong(key, defaultValue);
}
public static Boolean getBoolean(String key) {
return getProp().getBoolean(key);
}
public static Boolean getBoolean(String key, Boolean defaultValue) {
return getProp().getBoolean(key, defaultValue);
}
public static boolean containsKey(String key) {
return getProp().containsKey(key);
}
}
/**
* @desc:Prop can load properties file from CLASSPATH or File object
* @author:yanfei
* @date:2018/6/13
*/
public class Prop {
private Properties properties = null;
public static String DEFAULT_ENCODING = "UTF-8";
/**
* Prop constructor.
* @author Administrator
* @see #Prop(String, String)
*/
public Prop(String fileName) {
this(fileName, DEFAULT_ENCODING);
}
/**
* Prop constructor
* <p>
* Example:<br>
* Prop prop = new Prop("my_config.txt", "UTF-8");<br>
* String userName = prop.get("userName");<br>
* <br>
* prop = new Prop("com/file_in_sub_path_of_classpath.txt", "UTF-8");<br>
* String value = prop.get("key");
*
* @param fileName the properties file's name in classpath or the sub directory of classpath
* @param encoding the encoding
*/
public Prop(String fileName, String encoding) {
InputStream inputStream = null;
try {
// properties.load(Prop.class.getResourceAsStream(fileName));
inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
if (inputStream == null) {
throw new IllegalArgumentException("Properties file not found in classpath: " + fileName);
}
properties = new Properties();
properties.load(new InputStreamReader(inputStream, encoding));
} catch (IOException e) {
throw new RuntimeException("Error loading properties file.", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.getMessage();
}
}
}
}
/**
* Prop constructor.
*
* @see #Prop(File, String)
*/
public Prop(File file) {
this(file, DEFAULT_ENCODING);
}
/**
* Prop constructor
* <p>
* Example:<br>
* Prop prop = new Prop(new File("/var/config/my_config.txt"), "UTF-8");<br>
* String userName = prop.get("userName");
*
* @param file the properties File object
* @param encoding the encoding
*/
public Prop(File file, String encoding) {
if (file == null) {
throw new IllegalArgumentException("File can not be null.");
}
if (file.isFile() == false) {
throw new IllegalArgumentException("File not found : " + file.getName());
}
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
properties = new Properties();
properties.load(new InputStreamReader(inputStream, encoding));
} catch (IOException e) {
throw new RuntimeException("Error loading properties file.", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.getMessage();
}
}
}
}
public String get(String key) {
return properties.getProperty(key);
}
public String get(String key, String defaultValue) {
return properties.getProperty(key, defaultValue);
}
public Integer getInt(String key) {
return getInt(key, null);
}
public Integer getInt(String key, Integer defaultValue) {
String value = properties.getProperty(key);
if (value != null) {
return Integer.parseInt(value.trim());
}
return defaultValue;
}
public Long getLong(String key) {
return getLong(key, null);
}
public Long getLong(String key, Long defaultValue) {
String value = properties.getProperty(key);
if (value != null) {
return Long.parseLong(value.trim());
}
return defaultValue;
}
public Boolean getBoolean(String key) {
return getBoolean(key, null);
}
public Boolean getBoolean(String key, Boolean defaultValue) {
String value = properties.getProperty(key);
if (value != null) {
value = value.toLowerCase().trim();
if ("true".equals(value)) {
return true;
} else if ("false".equals(value)) {
return false;
}
throw new RuntimeException("The value can not parse to Boolean : " + value);
}
return defaultValue;
}
public boolean containsKey(String key) {
return properties.containsKey(key);
}
public Properties getProperties() {
return properties;
}
}
四、續