- ??作 ? ??????? 者:是江迪呀
- ??本文關(guān)鍵詞:
SpringBoot項(xiàng)目模版
、企業(yè)級(jí)
、模版
- ??每日?? 一言:
我們之所以這樣認(rèn)為,是因?yàn)樗麄冞@樣說。他們之所以那樣說,是因?yàn)樗麄兿胱屛覀兡菢诱J(rèn)為。所以實(shí)踐才是檢驗(yàn)真理的唯一準(zhǔn)則。
上回我們說了一些開發(fā)規(guī)范,其實(shí)現(xiàn)在你就可以開始寫代碼了。但是呢效率會(huì)很慢,實(shí)體類、mapper
、service
等等這些你都要手動(dòng)創(chuàng)建,這樣效率太低了,遇到一個(gè)表中有幾十個(gè)字段的情況,你可以一上午都在寫實(shí)體類,而且還不能保證準(zhǔn)確性,所以我們需要一個(gè)工具替我們生成。
一、使用Velocity模版自動(dòng)生成代碼
我們以生成t_user
表為例,表結(jié)構(gòu)如下:
Generator
代碼:
package com.shijiangdiya.common;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import java.util.*;
public class Generator {
/**
* 生成的代碼的頂層包名
*/
private static final String SERVICE_NAME = "code";
/**
* 最終包路徑
*/
private static final StringBuilder FINAL_PATH = new StringBuilder();
/**
* 表名前綴
*/
private static String tablePrefix = "t_";
/**
* <p>
* 讀取控制臺(tái)內(nèi)容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("請(qǐng)輸入" + tip + ":");
System.out.println(help);
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("請(qǐng)輸入正確的" + tip + "!");
}
/**
* 代碼生成器
*/
public static void main(String[] args) {
// 目標(biāo)數(shù)據(jù)表名
String[] tableName = scanner("表名,多個(gè)英文逗號(hào)分割").split(",");
generateByTables(tableName);
}
private static void generateByTables(String... tableNames) {
AutoGenerator mpg = new AutoGenerator();
mpg.setTemplateEngine(new VelocityTemplateEngine());
// 全局配置
GlobalConfig gc = globalGenerate();
// 包配置
PackageConfig pc = packageGenerate();
// 數(shù)據(jù)庫(kù)配置
DataSourceConfig dsc = dataSourceGenerate();
// 自定義模板
TemplateConfig tc = templateGenerate();
// 策略配置
StrategyConfig strategy = strategyGenerate(tableNames);
mpg.setGlobalConfig(gc);
mpg.setDataSource(dsc);
mpg.setPackageInfo(pc);
mpg.setTemplate(tc);
mpg.setStrategy(strategy);
mpg.execute();
}
/**
* 數(shù)據(jù)庫(kù)配置
*
* @return 數(shù)據(jù)源
*/
private static DataSourceConfig dataSourceGenerate() {
YamlPropertiesFactoryBean yamlMapFactoryBean = new YamlPropertiesFactoryBean();
yamlMapFactoryBean.setResources(new ClassPathResource("application.yml"));
//獲取yml里的參數(shù)
Properties properties = yamlMapFactoryBean.getObject();
String url = properties.getProperty("spring.datasource.url");
String driver = properties.getProperty("spring.datasource.driver-class-name");
String username = properties.getProperty("spring.datasource.username");
String password = properties.getProperty("spring.datasource.password");
// 數(shù)據(jù)庫(kù)配置
DataSourceConfig dsc = new DataSourceConfig();
//數(shù)據(jù)類型
dsc.setDbType(DbType.MYSQL);
dsc.setUrl(url);
dsc.setDriverName(driver);
dsc.setUsername(username);
dsc.setPassword(password);
return dsc;
}
/**
* 全局配置
*
* @return 全局配置
*/
private static GlobalConfig globalGenerate() {
// 全局配置
GlobalConfig gc = new GlobalConfig();
//是否覆蓋文件
gc.setFileOverride(true);
// 獲取頂層目錄
String projectPath = System.getProperty("user.dir");
// 獲取子項(xiàng)目目錄
String path = Generator.class.getClassLoader().getResource("").getPath();
String levelPath = path.substring(0, path.indexOf("target") - 1);
if (!projectPath.equals(levelPath)) {
FINAL_PATH.append(levelPath);
} else {
FINAL_PATH.append(projectPath);
}
//輸出路徑
gc.setOutputDir(FINAL_PATH + "/src/main/java");
//作者名稱
gc.setAuthor("shijiangdiya");
//生成后是否自動(dòng)打開文件
gc.setOpen(true);
// XML 二級(jí)緩存
gc.setEnableCache(false);
//是否使用swagger2
gc.setSwagger2(true);
// 自定義文件命名,注意 %s 會(huì)自動(dòng)填充表實(shí)體屬性!
gc.setControllerName("%sController");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
//mapper.xml中生成基礎(chǔ)resultMap
gc.setBaseResultMap(true);
//mapper.xml中生成基礎(chǔ)columnList
gc.setBaseColumnList(true);
// 主鍵類型
gc.setIdType(IdType.ID_WORKER);
return gc;
}
/**
* 策略配置
* 主要的表字段映射
*
* @param tableName 表名
* @return 策略配置
*/
private static StrategyConfig strategyGenerate(String[] tableName) {
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//表名映射到實(shí)體策略,帶下劃線的轉(zhuǎn)成 駝峰
strategy.setNaming(NamingStrategy.underline_to_camel);
//列名映射到類型屬性策略,帶下劃線的轉(zhuǎn)成駝峰
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// 表名和字段名是否大小寫
strategy.setCapitalMode(false);
//實(shí)體類使用lombok
strategy.setEntityLombokModel(true);
//controller使用rest接口模式
strategy.setRestControllerStyle(true);
// 繼承頂層controller 這里是
strategy.setSuperControllerClass("com.shijiangdiya.config.AbstractController");
//設(shè)置表名
strategy.setInclude(tableName);
//去掉前綴
strategy.setTablePrefix(tablePrefix);
strategy.setEntityBooleanColumnRemoveIsPrefix(true);
// 駝峰轉(zhuǎn)連字符
strategy.setControllerMappingHyphenStyle(true);
strategy.setEntityBuilderModel(true);
return strategy;
}
/**
* 自定義模板
*
* @return 模板
*/
private static TemplateConfig templateGenerate() {
// 設(shè)置自定義的模板
TemplateConfig tc = new TemplateConfig();
tc.setController("templates/MyController.java.vm")
.setEntity("templates/MyEntity.java.vm")
.setService("templates/MyService.java.vm")
.setServiceImpl("templates/MyServiceImpl.java.vm")
.setMapper("templates/MyMapper.java.vm")
.setXml("/templates/MyMapper.xml.vm");
// 不要源碼包內(nèi)的mapper
return tc;
}
/**
* 包配置
*
* @return 包配置
*/
private static PackageConfig packageGenerate() {
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(SERVICE_NAME);
pc.setParent("com.shijiangdiya");
pc.setEntity("entity");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setMapper("mapper");
pc.setXml("mapper.xml");
return pc;
}
}
二、自定義vm模版
使用自定義模板你可以生成更加符合你業(yè)務(wù)場(chǎng)景的代碼。
2.1 MyController.java.vm
在控制層中,提供了CRUD的方法,你可以自定義一些通用的東西,比如傳入查詢的QO、返回的DTO等。文章來源:http://www.zghlxwxcb.cn/news/detail-731792.html
package ${package.Controller};
import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import com.shijiangdiya.config.Response;
#if(${superControllerClassPackage})
import $!{superControllerClassPackage};
#end
/**
* <p>
* $!{table.comment} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/
#set($entityName = ${entity.substring(0,1).toLowerCase()}+${entity.substring(1)})
@RestController
@RequestMapping(value = {"#if(${controllerMappingHyphenStyle})/api/${controllerMappingHyphen}#else /api/${table.entityPath}#end"},
produces = MediaType.APPLICATION_JSON_VALUE)
@Api(value = "${table.controllerName}", description = "$!{table.comment}", produces = MediaType.APPLICATION_JSON_VALUE)
public class ${table.controllerName} extends ${superControllerClass} {
@Autowired
private ${table.serviceName} ${entityName}Service;
@ResponseBody
@ApiOperation(value = "", notes = "")
@GetMapping(value = "/")
public Response select(){
${entityName}Service.select();
return returnSuccess();
}
@ResponseBody
@ApiOperation(value = "", notes = "")
@PostMapping(value = "")
public Response add(){
${entityName}Service.add();
return returnSuccess();
}
@ResponseBody
@ApiOperation(value = "", notes = "")
@PutMapping(value = "/{id}")
public Response update(@PathVariable Long id){
${entityName}Service.modifyById();
return returnSuccess();
}
@ApiOperation(value = "$!{table.comment}-刪除", notes = "$!{table.comment}-刪除")
@DeleteMapping(value = "/{id}")
public Response delete(@PathVariable Long id){
${entityName}Service.deleteById(id);
return returnSuccess();
}
}
2.2 MyEntity.java.vm 實(shí)體類
package ${package.Controller};
import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import com.shijiangdiya.config.Response;
#if(${superControllerClassPackage})
import $!{superControllerClassPackage};
#end
/**
* <p>
* $!{table.comment} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/
#set($entityName = ${entity.substring(0,1).toLowerCase()}+${entity.substring(1)})
@RestController
@RequestMapping(value = {"#if(${controllerMappingHyphenStyle})/api/${controllerMappingHyphen}#else /api/${table.entityPath}#end"},
produces = MediaType.APPLICATION_JSON_VALUE)
@Api(value = "${table.controllerName}", description = "$!{table.comment}", produces = MediaType.APPLICATION_JSON_VALUE)
public class ${table.controllerName} extends ${superControllerClass} {
@Autowired
private ${table.serviceName} ${entityName}Service;
@ResponseBody
@ApiOperation(value = "", notes = "")
@GetMapping(value = "/")
public Response select(){
${entityName}Service.select();
return returnSuccess();
}
@ResponseBody
@ApiOperation(value = "", notes = "")
@PostMapping(value = "")
public Response add(){
${entityName}Service.add();
return returnSuccess();
}
@ResponseBody
@ApiOperation(value = "", notes = "")
@PutMapping(value = "/{id}")
public Response update(@PathVariable Long id){
${entityName}Service.modifyById();
return returnSuccess();
}
@ApiOperation(value = "$!{table.comment}-刪除", notes = "$!{table.comment}-刪除")
@DeleteMapping(value = "/{id}")
public Response delete(@PathVariable Long id){
${entityName}Service.deleteById(id);
return returnSuccess();
}
}
2.3 MyMapper.java.vm mapper接口
package ${package.Mapper};
import ${package.Entity}.${entity};
import ${superMapperClassPackage};
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* $!{table.comment} Mapper 接口
* </p>
*
* @author ${author}
* @since ${date}
*/
@Mapper
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
}
2.4 MyMapper.xml.vm mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${package.Mapper}.${table.mapperName}">
</mapper>
2.5 MyService.java.vm 服務(wù)層
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import java.util.List;
/**
* <p>
* $!{table.comment} 服務(wù)類
* </p>
*
* @author ${author}
* @since ${date}
*/
#set($entityName = ${entity.substring(0,1).toLowerCase()}+${entity.substring(1)})
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
/**
* 查詢
*/
List select();
/**
* 修改
*/
void add();
/**
* 刪除
* @param id
*/
void deleteById(Long id);
/**
* 修改
*/
void modifyById();
}
2.6 MyServiceImpl.java.vm 服務(wù)實(shí)現(xiàn)類
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
import java.util.List;
/**
* <p>
* $!{table.comment} 服務(wù)實(shí)現(xiàn)類
* </p>
*
* @author ${author}
* @since ${date}
* @version ${cfg.version}
*/
#set($entityName = ${entity.substring(0,1).toLowerCase()}+${entity.substring(1)})
@Service
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
@Override
public List select() {
return null;
}
@Override
public void add() {
}
@Override
public void deleteById(Long id) {
}
@Override
public void modifyById() {
}
}
三、測(cè)試
文章來源地址http://www.zghlxwxcb.cn/news/detail-731792.html
到了這里,關(guān)于【企業(yè)級(jí)SpringBoot單體項(xiàng)目模板 】——Mybatis-plus自動(dòng)代碼生成的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!