新项目需要使用spring boot,用freemarker写代码生成模板,能省下很多时间。
因为项目需要entity,requestVO,responseVO,所以需要获取数据库数据生成封装类。
废话不多说,上代码记录一下。
注:数据类型不全,我只写了我能用到的
maven文件配置
<dependencies>
<!-- 代码生成器依赖 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<!-- 代码生成器依赖 -->
<!--MyBatis 及 插件依赖 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.2.1</version>
</dependency>
<!--MyBatis 及 插件依赖 -->
<!--MySQL JDBC驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger2.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger2.version}</version>
</dependency>
<!-- swagger2 -->
<!--常用库依赖-->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!--常用库依赖-->
</dependencies>
获取数据库字段名,字段类型,注释等内容的工具类
package com.code.generator.utils;
import com.code.generator.model.BaseData;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author: Mr.Feng
* @create: 2018-08-06
**/
public class DatabaseUtil {
private final static Logger LOGGER = LoggerFactory.getLogger(DatabaseUtil.class);
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/erp?useUnicode=true&characterEncoding=utf8";
private static final String USERNAME = "root";
private static final String PASSWORD = "123456";
private static final String SQL = "SELECT * FROM ";
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
LOGGER.error("can not load jdbc driver", e);
}
}
/**
* 获取数据库连接
*
* @return
*/
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
LOGGER.error("get connection failure", e);
}
return conn;
}
/**
* 关闭数据库连接
* @param conn
*/
public static void closeConnection(Connection conn) {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
LOGGER.error("close connection failure", e);
}
}
}
/**
* 获取表中字段名称
* @param tableName 表名
* @return
*/
public static List<String> getColumnNames(String tableName) {
List<String> columnNames = new ArrayList<>();
//与数据库的连接
Connection conn = getConnection();
PreparedStatement pStemt = null;
String tableSql = SQL + tableName;
try {
pStemt = conn.prepareStatement(tableSql);
//结果集元数据
ResultSetMetaData rsmd = pStemt.getMetaData();
//表列数
int size = rsmd.getColumnCount();
for (int i = 0; i < size; i++) {
columnNames.add(rsmd.getColumnName(i + 1));
}
} catch (SQLException e) {
LOGGER.error("getColumnNames failure", e);
} finally {
if (pStemt != null) {
try {
pStemt.close();
closeConnection(conn);
} catch (SQLException e) {
LOGGER.error("getColumnNames close pstem and connection failure", e);
}
}
}
return columnNames;
}
/**
* 获取表中所有字段类型
* @param tableName
* @return
*/
public static List<String> getColumnTypes(String tableName) {
List<String> columnTypes = new ArrayList<>();
//与数据库的连接
Connection conn = getConnection();
PreparedStatement pStemt = null;
String tableSql = SQL + tableName;
try {
pStemt = conn.prepareStatement(tableSql);
//结果集元数据
ResultSetMetaData rsmd = pStemt.getMetaData();
//表列数
int size = rsmd.getColumnCount();
for (int i = 0; i < size; i++) {
columnTypes.add(rsmd.getColumnTypeName(i + 1));
}
} catch (SQLException e) {
LOGGER.error("getColumnTypes failure", e);
} finally {
if (pStemt != null) {
try {
pStemt.close();
closeConnection(conn);
} catch (SQLException e) {
LOGGER.error("getColumnTypes close pstem and connection failure", e);
}
}
}
return columnTypes;
}
/**
* 获取表中字段的注释
* @param tableName
* @return
*/
public static List<String> getColumnComments(String tableName) {
List<String> columnTypes = new ArrayList<>();
Connection conn = getConnection();
PreparedStatement pStemt = null;
String tableSql = SQL + tableName;
List<String> columnComments = new ArrayList<>();
ResultSet rs = null;
try {
pStemt = conn.prepareStatement(tableSql);
rs = pStemt.executeQuery("show full columns from " + tableName);
while (rs.next()) {
columnComments.add(rs.getString("Comment"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
closeConnection(conn);
} catch (SQLException e) {
LOGGER.error("getColumnComments close ResultSet and connection failure", e);
}
}
}
return columnComments;
}
public static void main(String[] args) {
String tableName = "e_vision_questionnaire";
List<BaseData> table = getBaseDataList("e_vision_questionnaire");
System.out.println(tableName);
}
public static List<BaseData> getBaseDataList(String tableName){
List<String> columnNames = getColumnNames(tableName);
List<String> columnTypes = getColumnTypes(tableName);
List<String> columnComments = getColumnComments(tableName);
List<BaseData> list = new ArrayList<BaseData>();
for (int i = 0 ; i<columnNames.size(); i++){
BaseData baseData = new BaseData();
baseData.setColumnName(firstUpperCamelCase(columnNames.get(i)));
String columnType = null;
switch (columnTypes.get(i)){
case "VARCHAR":
columnType = "String";
break;
case "DATETIME":
columnType = "Date";
break;
case "INT":
columnType = "Integer";
break;
case "TINYINT":
columnType = "Integer";
break;
case "DECIMAL":
columnType = "BigDecimal";
break;
case "TEXT":
columnType = "String";
break;
default:
columnType = "未知类型";
System.out.print("存在不支持类型!请手写。");
break;
}
baseData.setColumnType(columnType);
baseData.setColumnComment(columnComments.get(i));
list.add(baseData);
}
return list;
}
public static String firstUpperCamelCase(String str) {
if (StringUtils.isNotBlank(str)) {
str = str.replace("T_", "");
str = str.toLowerCase();
String[] strs = str.split("_");
if (strs.length == 1) {
return str.substring(0, 1).toLowerCase()+ str.substring(1);
} else {
String convertedStr = "";
for (int i = 0; i < strs.length; i++) {
convertedStr += firstLetterUpper(strs[i]);
}
return convertedStr.substring(0, 1).toLowerCase()+ convertedStr.substring(1);
}
}
return str;
}
public static String firstLetterUpper(String str) {
if (StringUtils.isNotBlank(str)) {
str = str.replace("T_", "");
str = str.toLowerCase();
return str.substring(0, 1).toUpperCase()
+ str.substring(1, str.length());
}
return str;
}
}
实体类,用于储存从数据库获取的数据
package com.code.generator.model;
/**
* @author: Mr.Feng
* @create: 2018-08-07
**/
public class BaseData {
private String columnComment;
private String columnType;
private String columnName;
public String getColumnComment() {
return columnComment;
}
public void setColumnComment(String columnComment) {
this.columnComment = columnComment;
}
public String getColumnType() {
return columnType;
}
public void setColumnType(String columnType) {
this.columnType = columnType;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
}
生成代码主程序
package com.code.generator;
import com.code.generator.model.BaseData;
import com.code.generator.utils.DatabaseUtil;
import com.google.common.base.CaseFormat;
import freemarker.template.TemplateExceptionHandler;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.*;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by L on 2018/5/29.
*/
public class CodeGenerator {
/**
* JDBC配置,请修改为你项目的实际配置
*/
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/data";
private static final String JDBC_USERNAME = "root";
private static final String JDBC_PASSWORD = "root";
private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
/**
* 模块名称
*/
static final String MODULE_NAME = "code";
/**
* 模块路径
*/
static final String MODULE_DIR = "/erp-admin-" + CodeGenerator.MODULE_NAME;
/**
* 模块基础路径
*/
public static final String BASE_PACKAGE = "com.erp.admin." + CodeGenerator.MODULE_NAME;
/**
* Model所在包
*/
public static final String MODEL_PACKAGE = BASE_PACKAGE + ".model";
/**
* Mapper所在包
*/
public static final String MAPPER_PACKAGE = BASE_PACKAGE + ".dao";
/**
* Mapper插件基础接口的完全限定名
*/
public static final String MAPPER_INTERFACE_REFERENCE = "com.erp.admin.common.core.Mapper";
/**
* 项目在硬盘上的基础路径
*/
private static final String PROJECT_PATH = System.getProperty("user.dir");
/**
* 模板位置
*/
private static final String TEMPLATE_FILE_PATH = PROJECT_PATH + "/code-generator/src/main/resources/generatorTemplate";
/**
* java文件路径
*/
private static final String JAVA_PATH = MODULE_DIR + "/src/main/java/";
/**
* 资源文件路径
*/
private static final String RESOURCES_PATH = MODULE_DIR + "/src/main/resources";
/**
* 生成的Service存放路径
*/
private static final String PACKAGE_PATH_SERVICE = "/com/erp/admin/" + CodeGenerator.MODULE_NAME + "/service/";
/**
* 生成的Service实现存放路径
*/
private static final String PACKAGE_PATH_SERVICE_IMPL = "/com/erp/admin/" + CodeGenerator.MODULE_NAME + "/service/impl/";
/**
* 生成的Controller存放路径
*/
private static final String PACKAGE_PATH_CONTROLLER = "/com/erp/admin/" + CodeGenerator.MODULE_NAME + "/controller/";
/**
* 生成的RequestVO存放路径
*/
private static final String PACKAGE_PATH_REQUESTVO = "/com/erp/admin/" + CodeGenerator.MODULE_NAME + "/vo/request/";
/**
* 生成的ResponseVO存放路径
*/
private static final String PACKAGE_PATH_RESPONSEVO = "/com/erp/admin/" + CodeGenerator.MODULE_NAME + "/vo/Response/";
/**
* 生成的EntityVO存放路径
*/
private static final String PACKAGE_PATH_ENTITYVO = "/com/erp/admin/" + CodeGenerator.MODULE_NAME + "/vo/Entity/";
private static final String AUTHOR = "Mr.Feng";
private static final String DATE = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
public static void main(String[] args) {
genCode("e_vision_binocularvisualfunc");
//genCode("输入表名","输入自定义Model名称");
}
/**
* 通过数据表名称生成代码,Model 名称通过解析数据表名称获得,下划线转大驼峰的形式。
* 如输入表名称 "t_user_detail" 将生成 TUserDetail、TUserDetailMapper、TUserDetailService ...
* @param tableNames 数据表名称...
*/
public static void genCode(String... tableNames) {
for (String tableName : tableNames) {
genCode(tableName, null);
}
}
/**
* 通过数据表名称,和自定义的 Model 名称生成代码
* 如输入表名称 "t_user_detail" 和自定义的 Model 名称 "User" 将生成 User、UserMapper、UserService ...
* @param tableName 数据表名称
* @param modelName 自定义的 Model 名称
*/
public static void genCode(String tableName, String modelName) {
File file1 = new File(PROJECT_PATH + JAVA_PATH);
File file2 = new File(PROJECT_PATH + RESOURCES_PATH);
if (!file1.getAbsoluteFile().exists()) {
file1.getAbsoluteFile().mkdirs();
}
if (!file2.getAbsoluteFile().exists()) {
file2.getAbsoluteFile().mkdirs();
}
//(tableName, modelName);
genController(tableName, modelName);
genService(tableName, modelName);
genModelAndMapper(tableName, modelName);
genEntityVO(tableName,modelName);
genRequestVO(tableName,modelName);
genResponseVO(tableName,modelName);
}
public static void genModelAndMapper(String tableName, String modelName) {
Context context = new Context(ModelType.FLAT);
context.setId("Potato");
context.setTargetRuntime("MyBatis3Simple");
context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`");
context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`");
JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
jdbcConnectionConfiguration.setConnectionURL(JDBC_URL);
jdbcConnectionConfiguration.setUserId(JDBC_USERNAME);
jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD);
jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME);
context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);
PluginConfiguration pluginConfiguration = new PluginConfiguration();
pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin");
pluginConfiguration.addProperty("mappers", CodeGenerator.MAPPER_INTERFACE_REFERENCE);
context.addPluginConfiguration(pluginConfiguration);
JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
javaModelGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
javaModelGeneratorConfiguration.setTargetPackage(CodeGenerator.MODEL_PACKAGE);
context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);
SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
sqlMapGeneratorConfiguration.setTargetProject(PROJECT_PATH + RESOURCES_PATH);
sqlMapGeneratorConfiguration.setTargetPackage("mapper");
context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);
JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
javaClientGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
javaClientGeneratorConfiguration.setTargetPackage(CodeGenerator.MAPPER_PACKAGE);
javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);
TableConfiguration tableConfiguration = new TableConfiguration(context);
tableConfiguration.setTableName(tableName);
tableConfiguration.setDomainObjectName(modelName);
tableConfiguration.setGeneratedKey(new GeneratedKey("id", "Mysql", true, null));
context.addTableConfiguration(tableConfiguration);
List<String> warnings;
MyBatisGenerator generator;
try {
Configuration config = new Configuration();
config.addContext(context);
config.validate();
boolean overwrite = true;
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
warnings = new ArrayList<String>();
generator = new MyBatisGenerator(config, callback, warnings);
generator.generate(null);
} catch (Exception e) {
throw new RuntimeException("生成Model和Mapper失败", e);
}
if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) {
throw new RuntimeException("生成Model和Mapper失败:" + warnings);
}
if (StringUtils.isEmpty(modelName)){
modelName = tableNameConvertUpperCamel(tableName);
}
System.out.println(modelName + ".java 生成成功");
System.out.println(modelName + "Mapper.java 生成成功");
System.out.println(modelName + "Mapper.xml 生成成功");
}
public static void genService(String tableName, String modelName) {
try {
freemarker.template.Configuration cfg = getConfiguration();
Map<String, Object> data = new HashMap<>();
data.put("date", DATE);
data.put("author", AUTHOR);
String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
data.put("modelNameUpperCamel", modelNameUpperCamel);
data.put("modelNameLowerCamel", tableNameConvertLowerCamel(tableName));
data.put("basePackage", CodeGenerator.BASE_PACKAGE);
File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_SERVICE + modelNameUpperCamel + "Service.java");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
cfg.getTemplate("service.ftl").process(data,
new FileWriter(file));
System.out.println(modelNameUpperCamel + "Service.java 生成成功");
File file1 = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_SERVICE_IMPL + modelNameUpperCamel + "ServiceImpl.java");
if (!file1.getParentFile().exists()) {
file1.getParentFile().mkdirs();
}
cfg.getTemplate("service-impl.ftl").process(data,
new FileWriter(file1));
System.out.println(modelNameUpperCamel + "ServiceImpl.java 生成成功");
} catch (Exception e) {
throw new RuntimeException("生成Service失败", e);
}
}
public static void genController(String tableName, String modelName) {
try {
freemarker.template.Configuration cfg = getConfiguration();
//
String[] split = tableName.split("_");
String tableLastName = split[2];
//
String modelLastName = firstToCapital(tableLastName);
Map<String, Object> data = new HashMap<>();
data.put("date", DATE);
data.put("author", AUTHOR);
String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
data.put("baseRequestMapping", modelNameConvertMappingPath(modelNameUpperCamel));
data.put("modelNameUpperCamel", modelNameUpperCamel);
data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
data.put("basePackage", CodeGenerator.BASE_PACKAGE);
data.put("tableLastName", tableLastName);
data.put("modelLastName", modelLastName);
data.put("modelName", MODULE_NAME);
File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_CONTROLLER + modelNameUpperCamel + "Controller.java");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
cfg.getTemplate("controller.ftl").process(data, new FileWriter(file));
System.out.println(modelNameUpperCamel + "Controller.java 生成成功");
} catch (Exception e) {
throw new RuntimeException("生成Controller失败", e);
}
}
public static void genRequestVO(String tableName, String modelName) {
genVO(tableName,modelName,PACKAGE_PATH_REQUESTVO,"RequestVO");
}
public static void genResponseVO(String tableName, String modelName) {
genVO(tableName,modelName,PACKAGE_PATH_RESPONSEVO,"ResponseVO");
}
public static void genEntityVO(String tableName, String modelName) {
genVO(tableName,modelName,PACKAGE_PATH_ENTITYVO,"EntityVO");
}
public static void genVO(String tableName, String modelName,String packagePath,String className) {
try {
freemarker.template.Configuration cfg = getConfiguration();
//
List<BaseData> baseDataList = DatabaseUtil.getBaseDataList(tableName);
Map<String, Object> data = new HashMap<>();
data.put("date", DATE);
data.put("author", AUTHOR);
String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
data.put("baseRequestMapping", modelNameConvertMappingPath(modelNameUpperCamel));
data.put("modelNameUpperCamel", modelNameUpperCamel);
data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
data.put("basePackage", CodeGenerator.BASE_PACKAGE);
data.put("baseDataList", baseDataList);
File file = new File(PROJECT_PATH + JAVA_PATH + packagePath + modelNameUpperCamel + className +".java");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
cfg.getTemplate(className +".ftl").process(data, new FileWriter(file));
System.out.println(modelNameUpperCamel + className + ".java 生成成功");
} catch (Exception e) {
throw new RuntimeException(className, e);
}
}
private static freemarker.template.Configuration getConfiguration() throws IOException {
freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_FILE_PATH));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
return cfg;
}
private static String tableNameConvertLowerCamel(String tableName) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, tableName.toLowerCase());
}
private static String tableNameConvertUpperCamel(String tableName) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase());
}
private static String tableNameConvertMappingPath(String tableName) {
//兼容使用大写的表名
tableName = tableName.toLowerCase();
return "/" + (tableName.contains("_") ? tableName.replaceAll("_", "/") : tableName);
}
private static String modelNameConvertMappingPath(String modelName) {
String tableName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, modelName);
return tableNameConvertMappingPath(tableName);
}
private static String packageConvertPath(String packageName) {
return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", "/") : packageName);
}
//首字母大写
private static String firstToCapital(String str){
char[] chars = str.toCharArray();
if (chars[0] >= 'a' && chars[0] <= 'z') {
chars[0] = (char)(chars[0] - 32);
}
return new String(chars);
}
}
在main函数里输入表名,就能自动生成model,controller,service,serviceimpl,dao,mapper,entityVO,requestVO,responseVO了
下面是freemarker模板(.ftl格式)
model,dao,mapper不需要模板,mybatis自带能直接生成。
controller模板
package ${basePackage}.controller;
import com.erp.admin.common.annotation.MyOperationLog;
import com.erp.admin.common.authorization.annotation.Authorization;
import com.erp.admin.common.constant.ResultCode;
import com.erp.admin.common.core.PageResult;
import com.erp.admin.common.core.Result;
import ${basePackage}.service.${modelNameUpperCamel}Service;
import ${basePackage}.vo.entity.${modelNameUpperCamel}EntityVO;
import ${basePackage}.vo.request.${modelNameUpperCamel}RequestVO;
import ${basePackage}.vo.response.${modelNameUpperCamel}ResponseVO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author: ${author}
* @create: ${date}
**/
@Slf4j
@RestController
@RequestMapping(value = "${baseRequestMapping}")
public class ${modelNameUpperCamel}Controller {
@Autowired
private ${modelNameUpperCamel}Service ${modelNameLowerCamel}Service;
@RequestMapping(value = "/listPage", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiOperation("获取列表")
@MyOperationLog
public ResponseEntity<Result<PageResult<${modelNameUpperCamel}ResponseVO>>> get${modelLastName}PageList(${modelNameUpperCamel}RequestVO ${modelNameLowerCamel}RequestVO) {
List<${modelNameUpperCamel}ResponseVO> ${modelNameLowerCamel}ResponseVOList = this.${modelNameLowerCamel}Service.query${modelNameUpperCamel}PageList(${modelNameLowerCamel}RequestVO);
Integer number = this.${modelNameLowerCamel}Service.query${modelNameUpperCamel}Count(${modelNameLowerCamel}RequestVO);
PageResult<${modelNameUpperCamel}ResponseVO> pageResult = new PageResult<${modelNameUpperCamel}ResponseVO>();
pageResult.setDataList(${modelNameLowerCamel}ResponseVOList);
pageResult.setTotal(number);
return new ResponseEntity<>(Result.ok(pageResult), HttpStatus.OK);
}
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiOperation("获取信息")
@MyOperationLog
@Authorization(permission="${modelName}:${tableLastName}:view")
@ApiImplicitParams({
@ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
})
public ResponseEntity<Result<${modelNameUpperCamel}EntityVO>> get${modelLastName}(@RequestParam String id) {
${modelNameUpperCamel}EntityVO ${modelNameLowerCamel}EntityVO = this.${modelNameLowerCamel}Service.get${modelNameUpperCamel}EntityVO(id);
return new ResponseEntity<>(Result.ok(${modelNameLowerCamel}EntityVO), HttpStatus.OK);
}
@RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiOperation("新增")
@MyOperationLog
@Authorization(permission="${modelName}:${tableLastName}:add")
@ApiImplicitParams({
@ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
})
public ResponseEntity<Result<Object>> add${modelLastName}(@RequestBody @Validated ${modelNameUpperCamel}EntityVO ${modelNameLowerCamel}EntityVO, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return this.getErrorMessage(bindingResult);
}
this.${modelNameLowerCamel}Service.add${modelNameUpperCamel}(${modelNameLowerCamel}EntityVO);
return new ResponseEntity<>(Result.ok(null), HttpStatus.OK);
}
@RequestMapping(value = "/update", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiOperation("更新")
@MyOperationLog
@Authorization(permission="${modelName}:${tableLastName}:update")
@ApiImplicitParams({
@ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
})
public ResponseEntity<Result<Object>> update${modelLastName}(@RequestBody @Validated ${modelNameUpperCamel}EntityVO ${modelNameLowerCamel}EntityVO, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return this.getErrorMessage(bindingResult);
}
this.${modelNameLowerCamel}Service.update${modelNameUpperCamel}(${modelNameLowerCamel}EntityVO);
return new ResponseEntity<>(Result.ok(null), HttpStatus.OK);
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ApiOperation("删除")
@MyOperationLog
@Authorization(permission="${modelName}:${tableLastName}:delete")
@ApiImplicitParams({
@ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
})
public ResponseEntity<Result<Object>> delete${modelLastName}(@RequestParam String id) {
this.${modelNameLowerCamel}Service.delete${modelNameUpperCamel}(id);
return new ResponseEntity<>(Result.ok(null), HttpStatus.OK);
}
public ResponseEntity<Result<Object>> getErrorMessage(BindingResult bindingResult){
String errorMessage = "";
for (ObjectError objectError : bindingResult.getAllErrors()) {
errorMessage += objectError.getDefaultMessage();
}
return new ResponseEntity<>(Result.error(ResultCode.FAIL, errorMessage), HttpStatus.OK);
}
}
service模板
package ${basePackage}.service;
import ${basePackage}.model.${modelNameUpperCamel};
import com.erp.admin.common.core.Service;
import com.erp.admin.common.core.Service;
import ${basePackage}.model.${modelNameUpperCamel};
import ${basePackage}.vo.entity.${modelNameUpperCamel}EntityVO;
import ${basePackage}.vo.request.${modelNameUpperCamel}RequestVO;
import ${basePackage}.vo.response.${modelNameUpperCamel}ResponseVO;
import java.util.List;
/**
* @author: ${author}
* @create: ${date}
**/
public interface ${modelNameUpperCamel}Service extends Service<${modelNameUpperCamel}> {
/**
* 获取分页列表
* @param ${modelNameLowerCamel}RequestVO
* @return
*/
List<${modelNameUpperCamel}ResponseVO> query${modelNameUpperCamel}PageList(${modelNameUpperCamel}RequestVO ${modelNameLowerCamel}RequestVO);
/**
* 获取总条数
* @param ${modelNameLowerCamel}RequestVO
* @return
*/
Integer query${modelNameUpperCamel}Count(${modelNameUpperCamel}RequestVO ${modelNameLowerCamel}RequestVO);
/**
* 获取详细信息
* @param id
* @return
*/
${modelNameUpperCamel}EntityVO get${modelNameUpperCamel}EntityVO(String id);
/**
* 新增
* @param ${modelNameLowerCamel}EntityVO 系统用户实体数据
*/
void add${modelNameUpperCamel}(${modelNameUpperCamel}EntityVO ${modelNameLowerCamel}EntityVO);
/**
* 修改
* @param ${modelNameLowerCamel}EntityVO 系统用户实体数据
*/
void update${modelNameUpperCamel}(${modelNameUpperCamel}EntityVO ${modelNameLowerCamel}EntityVO);
/**
* 删除
* @param id
*/
void delete${modelNameUpperCamel}(String id);
}
serviceimpl模板
package ${basePackage}.service.impl;
import com.erp.admin.common.constant.CommonEnum;
import com.erp.admin.common.core.AbstractService;
import ${basePackage}.dao.${modelNameUpperCamel}Mapper;
import ${basePackage}.model.${modelNameUpperCamel};
import ${basePackage}.service.${modelNameUpperCamel}Service;
import ${basePackage}.vo.entity.${modelNameUpperCamel}EntityVO;
import ${basePackage}.vo.request.${modelNameUpperCamel}RequestVO;
import ${basePackage}.vo.response.${modelNameUpperCamel}ResponseVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Condition;
import java.util.LinkedList;
import java.util.List;
/**
* @author: ${author}
* @create: ${date}
**/
@Service
@Transactional
public class ${modelNameUpperCamel}ServiceImpl extends AbstractService<${modelNameUpperCamel}> implements ${modelNameUpperCamel}Service {
@Autowired
private ${modelNameUpperCamel}Mapper ${modelNameLowerCamel}Mapper;
/**
* 获取分页列表
* @param ${modelNameLowerCamel}RequestVO
* @return
*/
@Override
public List<${modelNameUpperCamel}ResponseVO> query${modelNameUpperCamel}PageList(${modelNameUpperCamel}RequestVO ${modelNameLowerCamel}RequestVO) {
List<${modelNameUpperCamel}ResponseVO> ${modelNameLowerCamel}ResponseVOList = new LinkedList<>();
Condition condition = new Condition(${modelNameUpperCamel}.class);
condition.createCriteria();
/*根据实际情况添加
if (!(StringUtils.isEmpty(${modelNameLowerCamel}RequestVO.getLoginName()))) {
condition.getOredCriteria().get(0).andLike("loginName", "%" + ${modelNameLowerCamel}RequestVO.getLoginName() + "%");
}
if (!(StringUtils.isEmpty(${modelNameLowerCamel}RequestVO.getLoginName()))) {
ondition.createCriteria().andEqualTo("userId", ${modelNameLowerCamel}RequestVO.getUserId());
}
*/
List<${modelNameUpperCamel}> ${modelNameLowerCamel}List = this.selectByCondition(condition);
if (${modelNameLowerCamel}List != null && ${modelNameLowerCamel}List.size() > 0) {
for (${modelNameUpperCamel} ${modelNameLowerCamel} : ${modelNameLowerCamel}List) {
${modelNameUpperCamel}ResponseVO ${modelNameLowerCamel}ListResponseVO = new ${modelNameUpperCamel}ResponseVO();
BeanUtils.copyProperties(${modelNameLowerCamel},${modelNameLowerCamel}ListResponseVO);
${modelNameLowerCamel}ResponseVOList.add(${modelNameLowerCamel}ListResponseVO);
}
}
return ${modelNameLowerCamel}ResponseVOList;
}
/**
* 获取总条数
* @param ${modelNameLowerCamel}RequestVO
* @return
*/
@Override
public Integer query${modelNameUpperCamel}Count(${modelNameUpperCamel}RequestVO ${modelNameLowerCamel}RequestVO) {
Condition condition = new Condition(${modelNameUpperCamel}.class);
condition.createCriteria();
/*根据实际情况添加
if (!(StringUtils.isEmpty(${modelNameLowerCamel}RequestVO.getLoginName()))) {
condition.getOredCriteria().get(0).andLike("loginName", "%" + ${modelNameLowerCamel}RequestVO.getLoginName() + "%");
}
if (!(StringUtils.isEmpty(${modelNameLowerCamel}RequestVO.getLoginName()))) {
ondition.createCriteria().andEqualTo("userId", ${modelNameLowerCamel}RequestVO.getUserId());
}
*/
return this.selectCountByCondition(condition);
}
/**
* 添加
* @param ${modelNameLowerCamel}EntityVO
*/
@Override
public void add${modelNameUpperCamel}(${modelNameUpperCamel}EntityVO ${modelNameLowerCamel}EntityVO) {
${modelNameUpperCamel} ${modelNameLowerCamel} = new ${modelNameUpperCamel}();
BeanUtils.copyProperties(${modelNameLowerCamel}EntityVO, ${modelNameLowerCamel});
this.insertSelective(${modelNameLowerCamel});
}
/**
* 修改
* @param ${modelNameLowerCamel}EntityVO
*/
@Override
public void update${modelNameUpperCamel}(${modelNameUpperCamel}EntityVO ${modelNameLowerCamel}EntityVO) {
${modelNameUpperCamel} ${modelNameLowerCamel} = this.selectByPrimaryKey(${modelNameLowerCamel}EntityVO.getId());
BeanUtils.copyProperties(${modelNameLowerCamel}EntityVO, ${modelNameLowerCamel});
this.updateByPrimaryKeySelective(${modelNameLowerCamel});
}
/**
* 删除
* @param id
*/
@Override
public void delete${modelNameUpperCamel}(String id) {
${modelNameUpperCamel} ${modelNameLowerCamel} = new ${modelNameUpperCamel}();
${modelNameLowerCamel}.setId(id);
${modelNameLowerCamel}.setStateFlag(CommonEnum.StateFlagEnum.STATE_FLAG_DELETE.getCode());
this.updateByPrimaryKeySelective(${modelNameLowerCamel});
}
/**
* 获取详细信息
* @param id
* @return
*/
@Override
public ${modelNameUpperCamel}EntityVO get${modelNameUpperCamel}EntityVO(String id) {
${modelNameUpperCamel} ${modelNameLowerCamel} = new ${modelNameUpperCamel}();
${modelNameLowerCamel}.setId(id);
${modelNameLowerCamel} = this.selectOne(${modelNameLowerCamel});
if(null == ${modelNameLowerCamel}){
return null;
}
${modelNameUpperCamel}EntityVO ${modelNameLowerCamel}EntityVO = new ${modelNameUpperCamel}EntityVO();
BeanUtils.copyProperties(${modelNameLowerCamel},${modelNameLowerCamel}EntityVO);
return ${modelNameLowerCamel}EntityVO;
}
}
entityVO模板
package ${basePackage}.vo.entity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* 实体类
* 根据需要删减无效参数
* @author: ${author}
* @create: ${date}
**/
@Data
public class ${modelNameUpperCamel}EntityVO {
<#list baseDataList as data>
@ApiModelProperty(value = "${data.columnComment}")
private ${data.columnType} ${data.columnName};
</#list>
}
requestVO模板
package ${basePackage}.vo.request;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* 请求实体类
* 根据需要删减无效参数
* @author: ${author}
* @create: ${date}
**/
@Data
public class ${modelNameUpperCamel}RequestVO {
@ApiModelProperty(value = "页码")
private Integer number;
@ApiModelProperty(value = "页数")
private Integer size;
<#list baseDataList as data>
@ApiModelProperty(value = "${data.columnComment}")
private ${data.columnType} ${data.columnName};
</#list>
}
responseVO模板
package ${basePackage}.vo.response;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* 列表实体类
* 根据需要删减无效参数
* @author: ${author}
* @create: ${date}
**/
@Data
public class ${modelNameUpperCamel}ResponseVO {
<#list baseDataList as data>
@ApiModelProperty(value = "${data.columnComment}")
private ${data.columnType} ${data.columnName};
</#list>
}