添加依賴:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wm</groupId>
<artifactId>yucodegenator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>yucodegenator</name>
<description>wm_yu mybatis代碼生成器</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--日誌打印-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- freemarker 模板引擎 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.2</version>
</dependency>
<!-- commons-lang3依賴 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
使用自定義的freemark模板引擎
所用到的模板引擎文件如下:
controller.java.ftl
package ${package.Controller};
import com.hfepay.common.core.bean.Result;
import com.hfepay.common.data.mybatis.bean.QueryPage;
import ${package.Entity}.${entity};
import ${cfg.parentPackage}.domain.${entity}DO;
import ${package.Service}.${table.serviceName};
import ${cfg.parentPackage}.query.${entity}Query;
import com.hfepay.common.core.bean.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
/**
* <p>
* ${table.comment!} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/
@Slf4j
@RestController
@RequestMapping("/ai/${table.entityPath}")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>
@Autowired
private ${entity}Service ${table.entityPath}Service;
/**
* 根據ID查詢
* @param id
* @return
*/
@GetMapping("/{id}")
public Result<${entity}DO> get(@PathVariable Long id) {
return ${table.entityPath}Service.selectById(id);
}
/**
* 根據ID刪除
* @param id
* @return
*/
@DeleteMapping("/{id}")
public Result<Boolean> delete(@PathVariable Long id){
return ${table.entityPath}Service.deleteById(id);
}
/**
* 添加
* @param ${table.entityPath}
* @return
*/
@PostMapping
public Result insert(@RequestBody ${entity} ${table.entityPath}){
return ${table.entityPath}Service.insert(${table.entityPath});
}
/**
* 修改
* @param ${table.entityPath}
* @return
*/
@PutMapping
public Result update(@RequestBody ${entity} ${table.entityPath}){
return ${table.entityPath}Service.update(${table.entityPath});
}
/**
* 分頁查詢
* @param current 查詢頁
* @param size 每頁顯示條數
* @param query 查詢參數
* @return
*/
@GetMapping("/page")
public Result<Page<${entity}DO>> page(Integer current,Integer size, ${entity}Query query){
return ${table.entityPath}Service.page(new QueryPage(current,size),query);
}
}
</#if>
dao.java.jfl
package ${cfg.parentPackage}.dao;
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import org.springframework.stereotype.Repository;
import com.hfepay.common.data.mybatis.bean.BaseDAO;
/**
* <p>
* ${table.comment!} 服務DAO層
* </p>
*
* @author ${author}
* @since ${date}
*/
@Repository
public class ${entity}DAO extends BaseDAO<${table.mapperName}, ${entity}> {
}
domian.java.jfl
package ${cfg.parentPackage}.domain;
import ${package.Entity}.${entity};
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import lombok.ToString;
/**
* <p>
* ${table.comment!} 領域模型
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
<#if superEntityClass??>
@EqualsAndHashCode(callSuper = true)
<#else>
@EqualsAndHashCode(callSuper = false)
</#if>
@Accessors(chain = true)
@ToString(callSuper = true)
</#if>
public class ${entity}DO extends ${entity}{
}
entity.java.jfl
package ${package.Entity};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#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;
import lombok.ToString;
</#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)
@ToString(callSuper = 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>
<#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>
}
query.java.jfl
package ${cfg.parentPackage}.query;
import lombok.Data;
import java.io.Serializable;
/**
* <p>
* ${table.comment!} 查詢
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
</#if>
public class ${entity}Query implements Serializable{
}
service.java.jfl
package ${package.Service};
import ${cfg.parentPackage}.dao.${entity}DAO;
import ${package.Entity}.${entity};
import ${cfg.parentPackage}.domain.${entity}DO;
import ${cfg.parentPackage}.query.${entity}Query;
import com.hfepay.common.core.bean.Result;
import com.hfepay.common.data.mybatis.bean.QueryPage;
import com.hfepay.common.data.mybatis.util.PageHelper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hfepay.common.core.bean.Page;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.hfepay.common.util.BeanUtils;
import java.util.Map;
import java.util.List;
/**
* <p>
* ${table.comment!} 服務實現類
* </p>
*
* @author ${author}
* @since ${date}
*/
@Service
public class ${table.serviceName}{
@Autowired
private ${entity}DAO ${table.entityPath}DAO;
/**
* 根據ID查詢
* @param id
* @return
*/
public Result<${entity}DO> selectById(Long id){
return Result.success(BeanUtils.copyProperties(${table.entityPath}DAO.getById(id),${entity}DO.class));
}
/**
* 根據ID刪除
* @param id
* @return
*/
public Result deleteById(Long id){
return ${table.entityPath}DAO.removeById(id)?Result.success():Result.failure();
}
/**
* 添加
* @param ${table.entityPath}
* @return
*/
public Result insert(${entity} ${table.entityPath}){
return ${table.entityPath}DAO.save(${table.entityPath})?Result.success():Result.failure();
}
/**
* 修改
* @param ${table.entityPath}
* @return
*/
public Result update(${entity} ${table.entityPath}){
return ${table.entityPath}DAO.updateById(${table.entityPath})?Result.success():Result.failure();
}
/**
* 統計總數
*
* @param query
* @return
*/
public Result<Integer> count(${entity}Query query) {
return Result.success(${table.entityPath}DAO.count(this.combineQuery(query)));
}
/**
* 列表查詢
* @param query
* @return
*/
public Result<List<${entity}DO>> list(${entity}Query query){
return Result.success(BeanUtils.copyListProperties(${table.entityPath}DAO.list(this.combineQuery(query)),${entity}DO.class));
}
/**
* 分頁查詢
* @param page
* @return
*/
public Result<Page<${entity}DO>> page(QueryPage page, ${entity}Query query){
return Result.success(PageHelper.newPage(${table.entityPath}DAO.page(page,this.combineQuery(query)),${entity}DO.class));
}
/**
* 組裝查詢條件
*
* @param query
* @return
*/
private QueryWrapper<${entity}> combineQuery(${entity}Query query) {
QueryWrapper<${entity}> wrapper = new QueryWrapper<>();
//todo 查詢條件 wrapper.eq("字段名","值")
return wrapper;
}
}
以上的模板文件放在
resources/templates文件夾下面
下面是生成的main類
package com.hfepay.ai.store;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* 代碼生成
*
* @author wm_yu
* @date 2018/12/10 17:08
*/
public class CodeGenerator {
/**
* 包名
*/
public static final String PACKAGE_NAME = "com.wm";
/**
* 模塊名
*/
public static final String MODULE_NAME = "codedemo";
/**
* 數據庫名
*/
public static final String DB_NAME = "ywm_test";
/**
* 數據庫表前綴
*/
public static final String[] TABLE_PREFIX = {};
/**
* 需要生成的表名,不填則生成全部表
*/
public static final String[] TABLE_NAME = {"user","role","user_role"};
/**
* 獲取當前項目的路徑
*/
public static final String PROJECT_PATH = System.getProperty("user.dir") + "/code-generator";
/**
* 代碼存儲路徑
*/
public static final String CODE_SAVE_PATH = PROJECT_PATH + "/src/main/java/" + StringUtils.join((PACKAGE_NAME + "." + MODULE_NAME).split("\\."), "/");
public static void main(String[] args) {
// 代碼生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(PROJECT_PATH + "/src/main/java");
gc.setAuthor("wm_yu");
gc.setOpen(false);
gc.setFileOverride(true);
gc.setServiceName("%sService");
gc.setBaseColumnList(true);
gc.setBaseResultMap(true);
gc.setDateType(DateType.ONLY_DATE);
mpg.setGlobalConfig(gc);
// 數據源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://172.16.19.28:3306/" + DB_NAME + "?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("AI@123ai");
dsc.setTypeConvert(new MySqlTypeConvert() {
@Override
public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
//將tinyint格式改爲Integer類型
if (fieldType.toLowerCase().contains("tinyint")) {
return DbColumnType.INTEGER;
}
return super.processTypeConvert(globalConfig, fieldType);
}
});
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(MODULE_NAME);
pc.setParent(PACKAGE_NAME);
mpg.setPackageInfo(pc);
// 自定義配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
HashMap<String, Object> hashMap = new HashMap<>(10);
hashMap.put("parentPackage", PACKAGE_NAME + "." + MODULE_NAME);
this.setMap(hashMap);
}
};
List<FileOutConfig> focList = new ArrayList<>();
//mapper xml類
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸入文件名稱
return CODE_SAVE_PATH + "/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
//service類
focList.add(new FileOutConfig("/templates/service.java.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸入文件名稱
return CODE_SAVE_PATH + "/service/" + tableInfo.getEntityName() + "Service" + StringPool.DOT_JAVA;
}
});
//dao 類
focList.add(new FileOutConfig("/templates/dao.java.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸入文件名稱
return CODE_SAVE_PATH + "/dao/" + tableInfo.getEntityName() + "DAO" + StringPool.DOT_JAVA;
}
});
//domain
focList.add(new FileOutConfig("/templates/domain.java.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸入文件名稱
return CODE_SAVE_PATH + "/domain/" + tableInfo.getEntityName() + "DO" + StringPool.DOT_JAVA;
}
});
//query查詢類
focList.add(new FileOutConfig("/templates/query.java.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸入文件名稱
return CODE_SAVE_PATH + "/query/" + tableInfo.getEntityName() + "Query" + StringPool.DOT_JAVA;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setTablePrefix(TABLE_PREFIX);
strategy.setNaming(NamingStrategy.underline_to_camel);
//數據庫下劃線轉駝峯格式
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//數據庫實體類的公共字段,沒有就註釋掉,按需求添加
//strategy.setSuperEntityClass("com.hfepay.common.data.mybatis.bean.BaseEntity");
//添加lombok註解
strategy.setEntityLombokModel(true);
//rest風格生成http形式
strategy.setRestControllerStyle(true);
//controller 父類,不需要就註釋掉,按需求添加
//strategy.setSuperControllerClass("com.hfepay.common.web.controller.BaseController");
if (TABLE_NAME.length > 0) {
strategy.setInclude(TABLE_NAME);
}
//自定義基礎的Entity類,公共字段 ,填入將在entity中不出現,如果註釋了父類,這個也註釋掉
//strategy.setSuperEntityColumns("id", "version", "create_time", "update_time");
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
//刪除自己不需要的目錄
deleteDir(new File(CODE_SAVE_PATH + "/service/impl"));
}
private static void deleteDir(File dir) {
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
deleteDir(files[i]);
}
}
dir.delete();
}
}
基本上看代碼中的註釋就可以了,根據自己的需要來進行配置
baseDao代碼,dao的超類
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.hfepay.common.data.mybatis.bean;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hfepay.common.data.mybatis.util.IdUtils;
import java.util.Collection;
import java.util.Date;
import java.util.function.Consumer;
public class BaseDAO<M extends BaseMapper<T>, T extends BaseEntity> extends ServiceImpl<M, T> {
public BaseDAO() {
}
public boolean save(T entity) {
if (entity.getId() == null) {
entity.setId(IdUtils.getId());
}
entity.setUpdateTime(new Date());
entity.setCreateTime(new Date());
return super.save(entity);
}
public boolean saveBatch(Collection<T> entityList, int batchSize) {
entityList.forEach((entity) -> {
if (entity.getId() == null) {
entity.setId(IdUtils.getId());
}
entity.setUpdateTime(new Date());
entity.setCreateTime(new Date());
});
return super.saveBatch(entityList, batchSize);
}
public boolean updateById(T entity) {
entity.setUpdateTime(new Date());
return super.updateById(entity);
}
}
點擊運行main方法,可以看到生成的代碼如下:
記錄下來,下次項目直接一鍵生成