柳巖主演《刺客信條:大明風雲》有聲劇已在喜馬拉雅開播
阿新 • • 發佈:2021-05-10
官方文件:https://mp.baomidou.com/guide/
1.maven 包
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> </dependency> <!-- <dependency>--> <!-- <groupId>com.baomidou</groupId>--> <!-- <artifactId>mybatis-plus-boot-starter</artifactId>--> <!-- <version>3.4.3</version>--> <!-- </dependency>--> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency>
2.執行類
import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.TableFill; import com.baomidou.mybatisplus.generator.config.po.TableInfo; 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; import java.util.List; import java.util.Scanner; // 演示例子,執行 main 方法控制檯輸入模組表名回車自動生成對應專案目錄中 public class 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.isNotBlank(ipt)) { return ipt; } } throw new MybatisPlusException("請輸入正確的" + tip + "!"); } 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("liuy");// 作者 gc.setOpen(false); // 生成完成後不彈出檔案框 gc.setFileOverride(true); // 檔案是否覆蓋 // gc.setIdType(IdType.ASSIGN_UUID); //主鍵策略 實體類主鍵ID型別 gc.setDateType(DateType.ONLY_DATE); gc.setSwagger2(true); // 是否開啟swagger gc.setActiveRecord(true); //【不懂】 活動記錄 不需要ActiveRecord特性的請改為false 是否支援AR模式 gc.setEnableCache(false);// XML 二級快取 gc.setBaseResultMap(true);//【不懂】 XML ResultMap xml對映檔案的配置 gc.setBaseColumnList(false);//【不懂】 XML columList xml對映檔案的配置 // 自定義檔案命名,注意 %s 會自動填充表實體屬性! gc.setControllerName("%sController"); gc.setServiceName("%sService"); gc.setServiceImplName("%sServiceImpl"); gc.setMapperName("%sMapper"); gc.setXmlName("%sMapper"); mpg.setGlobalConfig(gc); //2、設定資料來源 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setUrl("jdbc:mysql://amapmysqlsit01.mysql.database.chinacloudapi.cn:3306/amaplus?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Shanghai&useSSL=true&requireSSL=false"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("cnmsladm@amapmysqlsit01"); dsc.setPassword("Mslamapsit@o21"); mpg.setDataSource(dsc); //3、包的配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.msl.mafa"); // pc.setController("controller"); // 可以不用設定,預設是這個 // pc.setService("service"); // 同上 // pc.setServiceImpl("service.impl"); // 同上 // pc.setMapper("mapper"); // 預設是mapper // pc.setEntity("entity"); // 預設是entity // pc.setXml("mapping"); // 預設是預設是mapper.xml pc.setModuleName(scanner("模組名")); // 控制層請求地址的包名顯示 mpg.setPackageInfo(pc); //4、策略配置 StrategyConfig strategy = new StrategyConfig(); // strategy.setInclude(tables.split(",")); // 需要生成的表 設定要對映的表名 strategy.setInclude(scanner("表名,多個英文逗號分割").split(",")); strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); // 自動lombok; strategy.setCapitalMode(false); //【不懂】 開啟全域性大寫命名 strategy.setSuperMapperClass(null); //【不懂】 strategy.setSuperMapperClass("BaseMapper"); // 是否需要開啟特定規範字段 // if (true == isNormalize) { // 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); // 控制:true——生成@RsetController false——生成@Controller strategy.setControllerMappingHyphenStyle(true); // 【不知道是啥】 strategy.setEntityTableFieldAnnotationEnable(true); // 表字段註釋啟動 啟動模板中的這個 <#if table.convert> strategy.setEntityBooleanColumnRemoveIsPrefix(true); // 是否刪除實體類欄位的字首 strategy.setTablePrefix("mdm_"); // 去掉表名mdm_inf_rec_data中的 mdm_ 類名為InfRecData strategy.setControllerMappingHyphenStyle(false); // 控制層mapping的對映地址 false:infRecData true:inf_rec_data mpg.setStrategy(strategy); //模板生成器 mpg.setTemplateEngine(new FreemarkerTemplateEngine()); TemplateConfig tc = new TemplateConfig(); tc.setController("/templatesFreemaker/controller.java"); tc.setService("/templatesFreemaker/service.java"); tc.setServiceImpl("/templatesFreemaker/serviceImpl.java"); tc.setEntity("/templatesFreemaker/entity.java"); tc.setMapper("/templatesFreemaker/mapper.java"); tc.setXml("/templatesFreemaker/mapper.xml"); mpg.setTemplate(tc); mpg.execute(); //執行 } }
3.resource 下新建包templatesFreemaker放入模板
controller.java.ftl
package ${package.Controller}; import ${package.Service}.${table.serviceName}; import ${package.Entity}.${entity}; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.hong.generate.common.PageResult; import com.hong.generate.common.Result; import com.hong.generate.common.StatusCode; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; <#if restControllerStyle> import org.springframework.web.bind.annotation.RestController; <#else> import org.springframework.stereotype.Controller; </#if> <#if superControllerClassPackage??> import ${superControllerClassPackage}; </#if> /** * <p> * ${table.comment!} 前端控制器 * </p> * * @author ${author} * @since ${date} */ @Slf4j @Api(tags = "${table.comment!}") <#if restControllerStyle> @RestController <#else> @Controller </#if> @RequestMapping("<#if package.ModuleName??>/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>") <#if kotlin> class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if> <#else> <#if superControllerClass??> public class ${table.controllerName} extends ${superControllerClass} { <#else> public class ${table.controllerName} { @Autowired public ${table.serviceName} ${table.entityPath}Service; @ApiOperation(value = "新增") @PostMapping("/save") public Result save(@RequestBody ${entity} ${table.entityPath}){ ${table.entityPath}Service.save(${table.entityPath}); return new Result(StatusCode.SUCCESS,"儲存成功"); } @ApiOperation(value = "根據id刪除") @PostMapping("/delete/{id}") public Result delete(@PathVariable("id") Long id){ ${table.entityPath}Service.removeById(id); return new Result(StatusCode.SUCCESS,"刪除成功"); } @ApiOperation(value = "條件查詢") @PostMapping("/get") public Result list(@RequestBody ${entity} ${table.entityPath}){ List<${entity}> ${table.entityPath}List = ${table.entityPath}Service.list(new QueryWrapper<>(${table.entityPath})); return new Result(StatusCode.SUCCESS,"查詢成功",${table.entityPath}List); } @ApiOperation(value = "列表(分頁)") @GetMapping("/list/{pageNum}/{pageSize}") public Object list(@PathVariable("pageNum")Long pageNum, @PathVariable("pageSize")Long pageSize){ IPage<${entity}> page = ${table.entityPath}Service.page( new Page<>(pageNum, pageSize), null); return new Result(StatusCode.SUCCESS,"查詢成功",new PageResult<>(page.getTotal(),page.getRecords())); } @ApiOperation(value = "詳情") @GetMapping("/get/{id}") public Result get(@PathVariable("id") String id){ ${entity} ${table.entityPath} = ${table.entityPath}Service.getById(id); return new Result(StatusCode.SUCCESS,"查詢成功",${table.entityPath}); } @ApiOperation(value = "根據id修改") @PostMapping("/update/{id}") public Result update(@PathVariable("id") String id, @RequestBody ${entity} ${table.entityPath}){ ${table.entityPath}.setId(id); ${table.entityPath}Service.updateById(${table.entityPath}); return new Result(StatusCode.SUCCESS,"更新成功"); } </#if> } </#if>
entity.java.ftl
package ${package.Entity};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if table.convert>
import com.baomidou.mybatisplus.annotation.TableName;
</#if>
<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
<#if entityLombokModel>
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if>
/**
* <p>
* ${table.comment!}
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
<#if superEntityClass??>
@EqualsAndHashCode(callSuper = true)
<#else>
@EqualsAndHashCode(callSuper = false)
</#if>
@Accessors(chain = true)
</#if>
<#if table.convert>
@TableName("${table.name}")
</#if>
<#if swagger2>
@ApiModel(value = "${entity}物件", description = "${table.comment!}")
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity} implements Serializable {
</#if>
private static final long serialVersionUID = 1L;
<#-- ---------- BEGIN 欄位迴圈遍歷 ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="${field.propertyName}"/>
</#if>
<#if field.comment!?length gt 0>
//${field.comment}
<#if swagger2>
@ApiModelProperty(value = "${field.comment}")
<#else>
/**
* ${field.comment}
*/
</#if>
</#if>
<#if field.keyFlag>
<#-- 主鍵 -->
<#if field.keyIdentityFlag>
@TableId(value = "${field.name}", type = IdType.AUTO)
<#elseif idType??>
@TableId(value = "${field.name}", type = IdType.${idType})
<#elseif field.convert>
@TableId("${field.name}")
</#if>
<#-- 普通欄位 -->
<#elseif field.fill??>
<#-- ----- 存在欄位填充設定 ----->
<#if field.convert>
@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
<#else>
@TableField(fill = FieldFill.${field.fill})
</#if>
<#elseif field.convert>
@TableField("${field.name}")
</#if>
<#-- 樂觀鎖註解 -->
<#if (versionFieldName!"") == field.name>
@Version
</#if>
<#-- 邏輯刪除註解 -->
<#if (logicDeleteFieldName!"") == field.name>
@TableLogic
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
<#------------ END 欄位迴圈遍歷 ---------->
<#if !entityLombokModel>
<#list table.fields as field>
<#if field.propertyType == "boolean">
<#assign getprefix="is"/>
<#else>
<#assign getprefix="get"/>
</#if>
public ${field.propertyType} ${getprefix}${field.capitalName}() {
return ${field.propertyName};
}
<#if entityBuilderModel>
public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
<#else>
public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
</#if>
this.${field.propertyName} = ${field.propertyName};
<#if entityBuilderModel>
return this;
</#if>
}
</#list>
</#if>
<#if entityColumnConstant>
<#list table.fields as field>
public static final String ${field.name?upper_case} = "${field.name}";
</#list>
</#if>
<#if activeRecord>
@Override
protected Serializable pkVal() {
<#if keyPropertyName??>
return this.${keyPropertyName};
<#else>
return null;
</#if>
}
</#if>
<#if !entityLombokModel>
@Override
public String toString() {
return "${entity}{" +
<#list table.fields as field>
<#if field_index==0>
"${field.propertyName}=" + ${field.propertyName} +
<#else>
", ${field.propertyName}=" + ${field.propertyName} +
</#if>
</#list>
"}";
}
</#if>
}
mapper.java.ftl
<?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}">
<#if enableCache>
<!-- 開啟二級快取 -->
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
</#if>
<#if baseResultMap>
<!-- 通用查詢對映結果 -->
<resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
<#list table.fields as field>
<#if field.keyFlag><#--生成主鍵排在第一位-->
<id column="${field.name}" property="${field.propertyName}" />
</#if>
</#list>
<#list table.commonFields as field><#--生成公共欄位 -->
<result column="${field.name}" property="${field.propertyName}" />
</#list>
<#list table.fields as field>
<#if !field.keyFlag><#--生成普通欄位 -->
<result column="${field.name}" property="${field.propertyName}" />
</#if>
</#list>
</resultMap>
</#if>
<#if baseColumnList>
<!-- 通用查詢結果列 -->
<sql id="Base_Column_List">
<#list table.commonFields as field>
${field.name},
</#list>
${table.fieldNames}
</sql>
</#if>
</mapper>
service.java.ftl
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
/**
* <p>
* ${table.comment!} 服務類
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
}
</#if>
serviceImpl.java.ftl
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
/**
* <p>
* ${table.comment!} 服務實現類
* </p>
*
* @author ${author}
* @since ${date}
*/
@Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {
}
<#else>
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
}
</#if>