修改代码生成模板.

This commit is contained in:
lijiahang
2023-09-27 16:47:55 +08:00
parent 54dcd1098f
commit aa9a77d73b
22 changed files with 369 additions and 136 deletions

View File

@@ -56,16 +56,31 @@ npm run dev
com.orion.ops.launch.generator.CodeGenerator
// 生成的表为 system_role, 业务注释为 '角色', 业务包为 role
new GenTable("system_role", "角色", "role")
// 忽略生成对外 api
.ignoreApi()
// 忽略生成单元测试
.ignoreTest()
Template.create("system_role", "角色", "role")
// 生成 api
.enableProviderApi()
// 生成单元测试
.disableUnitTest()
// 生成缓存
.cache("user:role", "角色缓存")
// 缓存过期时间 1 DAY
.expire(1, TimeUnit.DAYS)
// 生成 vue 文件, 一级业务包为 user, 二级业务包为 role (前端命名只能使用脊柱命名法)
.vue("user", "role")
// 前端使用抽屉表单
.useDrawerForm()
// 前端代码生成的枚举对象 可变参数
.enums(RoleStatusEnum.class);
// 前端使用抽屉表单 (多字段使用)
.enableDrawerForm()
// 前端支持多选
.enableRowSelection()
// 枚举下拉框 替换的字段为 'type'
.enums("type")
// 枚举值为 APP HOST
.names("APP", "HOST")
// 设置参数为 label APP.label = '应用' HOST.label = '主机'
.values("label", "应用", "主机")
// 设置参数为 value APP.value = '1' HOST.value = '2'
.values("value", 1, 2)
// 设置参数为 color APP.color = 'blue' HOST.color = 'green'
.color("blue", "green")
.build(),
```

View File

@@ -5,6 +5,7 @@ import com.orion.ops.framework.redis.core.utils.RedisUtils;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
@@ -16,6 +17,7 @@ import org.springframework.data.redis.serializer.RedisSerializer;
* @version 1.0.0
* @since 2023/6/28 14:44
*/
@Lazy(value = false)
@AutoConfiguration
@AutoConfigureOrder(AutoConfigureOrderConst.FRAMEWORK_REDIS)
public class OrionRedisAutoConfiguration {

View File

@@ -40,6 +40,7 @@ public class BaseUnitTest {
OrionCommonAutoConfiguration.class,
// mock
OrionMockBeanTestConfiguration.class,
OrionMockRedisTestConfiguration.class,
// datasource
OrionDataSourceAutoConfiguration.class,
DruidDataSourceAutoConfigure.class,
@@ -50,7 +51,6 @@ public class BaseUnitTest {
OrionMybatisAutoConfiguration.class,
MybatisPlusAutoConfiguration.class,
// redis
OrionMockRedisTestConfiguration.class,
OrionRedisAutoConfiguration.class,
RedisAutoConfiguration.class,
RedissonAutoConfiguration.class,

View File

@@ -47,6 +47,8 @@ public class EntityRandoms {
}
return Randoms.randomBoolean();
});
// Collection
FACTORY.getStrategy().setDefaultNumberOfCollectionElements(RANDOM_COLLECTION_LENGTH);
}
@SafeVarargs

View File

@@ -17,7 +17,6 @@ import com.orion.ops.framework.mybatis.core.domain.BaseDO;
import com.orion.ops.framework.mybatis.core.mapper.IMapper;
import com.orion.ops.launch.generator.engine.VelocityTemplateEngine;
import com.orion.ops.launch.generator.template.Table;
import com.orion.ops.launch.generator.template.Template;
import org.apache.ibatis.annotations.Mapper;
import java.io.File;
@@ -44,19 +43,17 @@ public class CodeGenerator {
String module = "infra";
// 生成的表
Table[] tables = {
Template.create("preference", "用户偏好", "preference")
.enableProviderApi()
.cache("user:preference:{}:{}", "用户偏好 ${type} ${userId}")
.formatKeys("type", "userId")
.vue("user", "preference")
.enableDrawerForm()
.enableRowSelection()
.enums("type")
.names("APP", "HOST")
.values("label", "应用", "主机")
.values("value", 1, 2)
.color("blue", "green")
.build(),
// Template.create("preference", "用户偏好", "preference")
// .enableProviderApi()
// .cache("user:preference:{}:{}", "用户偏好 ${type} ${userId}")
// .expire(1, TimeUnit.HOURS)
// .vue("user", "preference")
// .enums("type")
// .names("APP", "HOST")
// .values("label", "应用", "主机")
// .values("value", 1, 2)
// .color("blue", "green")
// .build(),
};
// jdbc 配置 - 使用配置文件
File yamlFile = new File("orion-ops-launch/src/main/resources/application-dev.yaml");
@@ -319,6 +316,10 @@ public class CodeGenerator {
new String[]{"/templates/orion-server-module-entity-export.java.vm", "${type}Export.java", "entity.export"},
// convert 文件
new String[]{"/templates/orion-server-module-convert.java.vm", "${type}Convert.java", "convert"},
// cache dto 文件
new String[]{"/templates/orion-server-module-cache-dto.java.vm", "${type}CacheDTO.java", "entity.dto.${bizPackage}"},
// cache key define 文件
new String[]{"/templates/orion-server-module-cache-key-define.java.vm", "${type}CacheKeyDefine.java", "define"},
// -------------------- 后端 - provider --------------------
// api 文件
new String[]{"/templates/orion-server-provider-api.java.vm", "${type}Api.java", "api"},
@@ -395,10 +396,12 @@ public class CodeGenerator {
String line = AnsiAppender.create()
.append(AnsiForeground.BRIGHT_GREEN.and(AnsiFont.BOLD), "\n:: 代码生成完毕 ^_^ ::\n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- 后端代码复制后请先 clean 模块父工程\n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- 后端代码复制后请先执行单元测试检测是否正常\n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- 后端代码需要自行修改缓存逻辑\n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- 后端代码修改完成后请先执行单元测试检测是否正常\n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- vue 代码需要注意同一模块的 router 需要自行合并\n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- vue 枚举需要自行更改数据类型\n")
.append(AnsiForeground.BRIGHT_BLUE.and(AnsiFont.BOLD), "- 菜单 sql 执行完成后 需要在菜单页面刷新缓存\n")
.append(AnsiForeground.BRIGHT_RED.and(AnsiFont.BOLD), "- 数据库实体字段长度限制为最大 65535\n")
.toString();
System.out.print(line);
}

View File

@@ -87,9 +87,26 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
p.setProperty("file.resource.loader.unicode", StringPool.TRUE);
this.velocityEngine = new VelocityEngine(p);
}
// 处理表结构
this.getConfigBuilder().getTableInfoList().forEach(this::processTasble);
return this;
}
/**
* 处理表结构
*
* @param tableInfo tableInfo
*/
private void processTasble(TableInfo tableInfo) {
for (TableField field : tableInfo.getFields()) {
TableField.MetaInfo metaInfo = field.getMetaInfo();
// 限制字段长度最大为 65535
if (metaInfo.getLength() > 65535) {
Fields.setFieldValue(metaInfo, "length", 65535);
}
}
}
@Override
public void writer(@NotNull Map<String, Object> objectMap, @NotNull String templatePath, @NotNull File outputFile) throws Exception {
Template template = velocityEngine.getTemplate(templatePath, ConstVal.UTF8);
@@ -160,6 +177,10 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
if (!table.isEnableUnitTest()) {
files.removeIf(file -> this.isServerUnitTestFile(file.getTemplatePath()));
}
// 不生成缓存文件
if (!table.isEnableCache()) {
files.removeIf(file -> this.isServerCacheFile(file.getTemplatePath()));
}
// 不生成 vue 文件
if (!table.isEnableVue()) {
files.removeIf(file -> this.isVueFile(file.getTemplatePath()));
@@ -180,13 +201,24 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
objectMap.put("since", OrionOpsProConst.VERSION);
// 替换业务注释
tableInfo.setComment(tables.get(tableInfo.getName()).getComment());
Table table = tables.get(tableInfo.getName());
// 缓存元数据
Map<String, Object> cacheMeta = this.pickTableMeta(table,
"enableCache", "cacheKey", "cacheDesc",
"cacheExpired", "cacheExpireTime", "cacheExpireUnit");
objectMap.put("cacheMeta", cacheMeta);
// 实体名称
String domainName = tableInfo.getEntityName();
String mappingHyphen = objectMap.get("controllerMappingHyphen").toString();
String entityName = domainName.substring(0, domainName.length() - 2);
// 类型
objectMap.put("type", entityName);
// 类型首字母小写
objectMap.put("typeLower", Strings.firstLower(entityName));
// 类型脊柱名称
objectMap.put("typeHyphen", mappingHyphen.substring(0, mappingHyphen.length() - 3));
// 类型常量
objectMap.put("typeConst", VariableStyles.BIG_HUMP.toSpine(entityName).toUpperCase());
}
/**
@@ -244,16 +276,17 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
objectMap.put("apiComment", map);
String comment = tableInfo.getComment();
map.put("create", "创建" + comment);
map.put("updateAll", "更新" + comment);
map.put("updateById", "通过 id 更新" + comment);
map.put("getById", "通过 id 查询" + comment);
map.put("listByIdList", "通过 id 批量查询" + comment);
map.put("listAll", "查询" + comment);
map.put("queryCount", "查询" + comment + "数量");
map.put("updateAll", "根据条件更新" + comment);
map.put("updateById", "更新" + comment);
map.put("getById", "查询" + comment);
map.put("getByIdList", "批量查询" + comment);
map.put("queryList", "查询全部" + comment);
map.put("queryListByCache", "通过缓存查询" + comment);
map.put("queryPage", "分页查询" + comment);
map.put("deleteById", "通过 id 删除" + comment);
map.put("deleteAll", "删除" + comment);
map.put("batchDeleteByIdList", "通过 id 批量删除" + comment);
map.put("queryCount", "查询" + comment + "数量");
map.put("deleteById", "删除" + comment);
map.put("deleteAll", "根据条件删除" + comment);
map.put("batchDelete", "批量删除" + comment);
map.put("export", "导出" + comment);
}
@@ -270,7 +303,6 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
.filter(s -> this.isServerFile(s.getTemplatePath()))
.collect(Collectors.toList());
String parentPath = getPathInfo(OutputFile.parent);
// 生成文件
customFiles.forEach(file -> {
// 获取 parent package
@@ -279,13 +311,13 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
objectMap.put("currentPackage", currentPackage);
// 文件路径
String filePath = parentPath + File.separator + file.getPackageName()
String filePath = this.getPathInfo(OutputFile.parent) + File.separator + file.getPackageName()
.replaceAll("\\.", StringPool.BACK_SLASH + File.separator);
// 文件名称
Map<String, Object> meta = new HashMap<>(4);
meta.put("type", objectMap.get("type"));
meta.put("tableName", tableInfo.getName());
String fileName = filePath + File.separator + Strings.format(file.getFileName(), meta);
Map<String, Object> fileNameMeta = new HashMap<>(4);
fileNameMeta.put("type", objectMap.get("type"));
fileNameMeta.put("tableName", tableInfo.getName());
String fileName = filePath + File.separator + Strings.format(file.getFileName(), fileNameMeta);
// 渲染文件
this.outputFile(Files1.newFile(fileName), objectMap, file.getTemplatePath(), file.isFileOverride());
});
@@ -307,33 +339,31 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
customFiles = customFiles.stream()
.filter(s -> this.isVueFile(s.getTemplatePath()))
.collect(Collectors.toList());
// 元数据
String outPath = getConfigBuilder().getGlobalConfig().getOutputDir();
// 设置前端元数据
Table table = tables.get(tableInfo.getName());
BeanMap beanMap = BeanMap.create(table, "enums");
Map<String, Object> vueMeta = this.pickTableMeta(table, "enableDrawerForm", "enableRowSelection", "module", "feature");
// 模块名称实体
beanMap.put("moduleEntity", VariableStyles.SPINE.toBigHump(table.getModule()));
vueMeta.put("moduleEntity", VariableStyles.SPINE.toBigHump(table.getModule()));
// 模块名称实体
beanMap.put("moduleEntityFirstLower", Strings.firstLower(beanMap.get("moduleEntity")));
vueMeta.put("moduleEntityFirstLower", Strings.firstLower(vueMeta.get("moduleEntity")));
// 模块名称常量
beanMap.put("moduleConst", VariableStyles.SPINE.toSerpentine(table.getModule()).toUpperCase());
vueMeta.put("moduleConst", VariableStyles.SPINE.toSerpentine(table.getModule()).toUpperCase());
// 功能名称实体
beanMap.put("featureEntity", VariableStyles.SPINE.toBigHump(table.getFeature()));
vueMeta.put("featureEntity", VariableStyles.SPINE.toBigHump(table.getFeature()));
// 功能名称实体
beanMap.put("featureEntityFirstLower", Strings.firstLower(beanMap.get("featureEntity")));
vueMeta.put("featureEntityFirstLower", Strings.firstLower(vueMeta.get("featureEntity")));
// 功能名称常量
beanMap.put("featureConst", VariableStyles.SPINE.toSerpentine(table.getFeature()).toUpperCase());
vueMeta.put("featureConst", VariableStyles.SPINE.toSerpentine(table.getFeature()).toUpperCase());
// 枚举
beanMap.put("enums", this.getEnumMap(beanMap, tableInfo, table));
objectMap.put("vue", beanMap);
vueMeta.put("enums", this.getEnumMap(tableInfo, table));
objectMap.put("vue", vueMeta);
// 生成文件
customFiles.forEach(file -> {
// 文件路径
String filePath = outPath
+ "/" + Strings.format(file.getPackageName(), beanMap)
+ "/" + Strings.format(file.getFileName(), beanMap);
String filePath = getConfigBuilder().getGlobalConfig().getOutputDir()
+ "/" + Strings.format(file.getPackageName(), vueMeta)
+ "/" + Strings.format(file.getFileName(), vueMeta);
// 渲染文件
this.outputFile(Files1.newFile(filePath), objectMap, file.getTemplatePath(), file.isFileOverride());
});
@@ -379,6 +409,16 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
return templatePath.contains("orion-server-test");
}
/**
* 是否为后端缓存文件
*
* @param templatePath templatePath
* @return 是否为后端缓存文件
*/
private boolean isServerCacheFile(String templatePath) {
return templatePath.contains("orion-server-cache");
}
/**
* 是否为 vue 文件
*
@@ -390,15 +430,30 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
templatePath.contains("orion-sql-menu.sql");
}
/**
* 获取表元数据
*
* @param table table
* @param keys keys
* @return meta
*/
private Map<String, Object> pickTableMeta(Table table, String... keys) {
BeanMap beanMap = BeanMap.create(table);
Map<String, Object> tableMeta = new HashMap<>();
for (String key : keys) {
tableMeta.put(key, beanMap.get(key));
}
return tableMeta;
}
/**
* 获取枚举
*
* @param beanMap beanMap
* @param tableInfo tableInfo
* @param table table
* @return enumMap
*/
private Map<String, EnumMeta> getEnumMap(BeanMap beanMap, TableInfo tableInfo, Table table) {
private Map<String, EnumMeta> getEnumMap(TableInfo tableInfo, Table table) {
// 枚举值
Map<String, EnumMeta> enumMap = new LinkedHashMap<>();
for (VueEnum meta : table.getEnums()) {

View File

@@ -1,7 +1,5 @@
package com.orion.ops.launch.generator.template;
import com.orion.lang.utils.collect.Lists;
import java.util.concurrent.TimeUnit;
/**
@@ -64,17 +62,6 @@ public class CacheTemplate extends ServerTemplate {
return this;
}
/**
* 设置缓存格式化字段
*
* @param keys keys
* @return this
*/
public CacheTemplate formatKeys(String... keys) {
table.cacheFormatKeys.addAll(Lists.of(keys));
return this;
}
/**
* 设置缓存过期时间
*

View File

@@ -58,11 +58,6 @@ public class Table {
*/
protected String cacheDesc;
/**
* 缓存格式化字段
*/
protected List<String> cacheFormatKeys;
/**
* 缓存是否会过期
*/
@@ -111,7 +106,6 @@ public class Table {
protected List<VueEnum> enums;
protected Table() {
this.cacheFormatKeys = new ArrayList<>();
this.enums = new ArrayList<>();
}

View File

@@ -0,0 +1,45 @@
package ${currentPackage};
import io.swagger.v3.oas.annotations.media.Schema;
import java.io.Serializable;
import lombok.*;
import java.util.*;
import java.math.*;
/**
* $!{table.comment} 缓存对象
*
* @author ${author}
* @version ${since}
* @since ${date}
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(name = "${type}CacheDTO", description = "$!{table.comment} 缓存对象")
public class ${type}CacheDTO implements Serializable {
private static final long serialVersionUID = 1L;
#foreach($field in ${table.fields})
#if("$!field.comment" != "")
@Schema(description = "${field.comment}")
#end
private ${field.propertyType} ${field.propertyName};
#end
@Schema(description = "创建时间")
private Date createTime;
@Schema(description = "修改时间")
private Date updateTime;
@Schema(description = "创建人")
private String creator;
@Schema(description = "修改人")
private String updater;
}

View File

@@ -0,0 +1,29 @@
package ${currentPackage};
import com.orion.lang.define.cache.CacheKeyBuilder;
import com.orion.lang.define.cache.CacheKeyDefine;
#foreach($pkg in ${customModuleFilePackages})
import ${pkg}.*;
#end
import java.util.concurrent.TimeUnit;
/**
* $!{table.comment}缓存 key
*
* @author ${author}
* @version ${since}
* @since ${date}
*/
public interface ${type}CacheKeyDefine {
CacheKeyDefine $typeConst = new CacheKeyBuilder()
.key("$cacheMeta.cacheKey")
.desc("$cacheMeta.cacheDesc")
.type(${type}CacheDTO.class)
#if($cacheMeta.cacheExpired)
.timeout($cacheMeta.cacheExpireTime, TimeUnit.$cacheMeta.cacheExpireUnit.name())
#end
.build();
}

View File

@@ -29,13 +29,13 @@ GET {{baseUrl}}/${package.ModuleName}/${typeHyphen}/get?id=1
Authorization: {{token}}
${httpComment} ${apiComment.listByIdList}
GET {{baseUrl}}/${package.ModuleName}/${typeHyphen}/list?idList=1,2,3
${httpComment} ${apiComment.getByIdList}
GET {{baseUrl}}/${package.ModuleName}/${typeHyphen}/batch-get?idList=1,2,3
Authorization: {{token}}
${httpComment} ${apiComment.listAll}
POST {{baseUrl}}/${package.ModuleName}/${typeHyphen}/list-all
${httpComment} ${apiComment.queryList}
POST {{baseUrl}}/${package.ModuleName}/${typeHyphen}/list
Content-Type: application/json
Authorization: {{token}}
@@ -65,8 +65,8 @@ DELETE {{baseUrl}}/${package.ModuleName}/${typeHyphen}/delete?id=1
Authorization: {{token}}
${httpComment} ${apiComment.batchDeleteByIdList}
DELETE {{baseUrl}}/${package.ModuleName}/${typeHyphen}/delete-batch?idList=1,2,3
${httpComment} ${apiComment.batchDelete}
DELETE {{baseUrl}}/${package.ModuleName}/${typeHyphen}/batch-delete?idList=1,2,3
Authorization: {{token}}

View File

@@ -72,19 +72,19 @@ public class ${table.controllerName} {
}
@IgnoreLog(IgnoreLogMode.RET)
@GetMapping("/list")
@Operation(summary = "${apiComment.listByIdList}")
@GetMapping("/batch-get")
@Operation(summary = "${apiComment.getByIdList}")
@Parameter(name = "idList", description = "idList", required = true)
@PreAuthorize("@ss.hasPermission('${package.ModuleName}:${typeHyphen}:query')")
public List<${type}VO> get${type}List(@RequestParam("idList") List<Long> idList) {
public List<${type}VO> get${type}Batch(@RequestParam("idList") List<Long> idList) {
return ${typeLower}Service.get${type}ByIdList(idList);
}
@IgnoreLog(IgnoreLogMode.RET)
@PostMapping("/list-all")
@Operation(summary = "${apiComment.listAll}")
@PostMapping("/list")
@Operation(summary = "${apiComment.queryList}")
@PreAuthorize("@ss.hasPermission('${package.ModuleName}:${typeHyphen}:query')")
public List<${type}VO> get${type}ListAll(@Validated @RequestBody ${type}QueryRequest request) {
public List<${type}VO> get${type}List(@Validated @RequestBody ${type}QueryRequest request) {
return ${typeLower}Service.get${type}List(request);
}
@@ -104,8 +104,8 @@ public class ${table.controllerName} {
return ${typeLower}Service.delete${type}ById(id);
}
@DeleteMapping("/delete-batch")
@Operation(summary = "${apiComment.batchDeleteByIdList}")
@DeleteMapping("/batch-delete")
@Operation(summary = "${apiComment.batchDelete}")
@Parameter(name = "idList", description = "idList", required = true)
@PreAuthorize("@ss.hasPermission('${package.ModuleName}:${typeHyphen}:delete')")
public Integer batchDelete${type}(@RequestParam("idList") List<Long> idList) {

View File

@@ -33,4 +33,10 @@ public interface ${type}Convert {
List<${type}VO> to(List<${type}DO> list);
#if($cacheMeta.enableCache)
${type}VO to(${type}CacheDTO cache);
${type}CacheDTO toCache(${type}DO domain);
#end
}

View File

@@ -3,12 +3,17 @@ package ${package.ServiceImpl};
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.orion.lang.define.wrapper.DataGrid;
#if($cacheMeta.enableCache)
import com.orion.ops.framework.common.constant.Const;
#end
import com.orion.lang.utils.collect.Lists;
import com.orion.office.excel.writer.exporting.ExcelExport;
import com.orion.ops.framework.common.constant.ErrorMessage;
import com.orion.ops.framework.common.utils.FileNames;
import com.orion.ops.framework.common.constant.ErrorMessage;
import com.orion.ops.framework.common.utils.Valid;
#if($cacheMeta.enableCache)
import com.orion.ops.framework.redis.core.utils.RedisMaps;
#end
#foreach($pkg in ${customModuleFilePackages})
import ${pkg}.*;
#end
@@ -50,6 +55,10 @@ public class ${table.serviceImplName} implements ${table.serviceName} {
int effect = ${typeLower}DAO.insert(record);
Long id = record.getId();
log.info("${type}Service-create${type} id: {}, effect: {}", id, effect);
#if($cacheMeta.enableCache)
// 删除缓存
RedisMaps.delete(${type}CacheKeyDefine.${typeConst});
#end
return id;
}
@@ -67,6 +76,10 @@ public class ${table.serviceImplName} implements ${table.serviceName} {
// 更新
int effect = ${typeLower}DAO.updateById(updateRecord);
log.info("${type}Service-update${type}ById effect: {}", effect);
#if($cacheMeta.enableCache)
// 删除缓存
RedisMaps.delete(${type}CacheKeyDefine.${typeConst});
#end
return effect;
}
@@ -80,6 +93,10 @@ public class ${table.serviceImplName} implements ${table.serviceName} {
// 更新
int effect = ${typeLower}DAO.update(updateRecord, wrapper);
log.info("${type}Service.update${type} effect: {}", effect);
#if($cacheMeta.enableCache)
// 删除缓存
RedisMaps.delete(${type}CacheKeyDefine.${typeConst});
#end
return effect;
}
@@ -111,6 +128,32 @@ public class ${table.serviceImplName} implements ${table.serviceName} {
return ${typeLower}DAO.of(wrapper).list(${type}Convert.MAPPER::to);
}
#if($cacheMeta.enableCache)
@Override
public List<${type}VO> get${type}ListByCache() {
// 查询缓存
List<${type}CacheDTO> list = RedisMaps.valuesJson(${type}CacheKeyDefine.${typeConst});
if (list.isEmpty()) {
// 查询数据库
list = ${typeLower}DAO.of().list(${type}Convert.MAPPER::toCache);
// 添加默认值 防止穿透
if (list.isEmpty()) {
list.add(${type}CacheDTO.builder()
.id(Const.NONE_ID)
.build());
}
// 设置缓存
RedisMaps.putAllJson(${type}CacheKeyDefine.${typeConst}.getKey(), s -> s.getId().toString(), list);
RedisMaps.setExpire(${type}CacheKeyDefine.${typeConst});
}
// 删除默认值
return list.stream()
.filter(s -> !s.getId().equals(Const.NONE_ID))
.map(${type}Convert.MAPPER::to)
.collect(Collectors.toList());
}
#end
@Override
public Long get${type}Count(${type}QueryRequest request) {
// 条件
@@ -137,7 +180,11 @@ public class ${table.serviceImplName} implements ${table.serviceName} {
Valid.notNull(record, ErrorMessage.DATA_ABSENT);
// 删除
int effect = ${typeLower}DAO.deleteById(id);
log.info("${type}Service-delete${type}ById effect: {}", effect);
log.info("${type}Service-delete${type}ById id: {}, effect: {}", id, effect);
#if($cacheMeta.enableCache)
// 删除缓存
RedisMaps.delete(${type}CacheKeyDefine.${typeConst}, id);
#end
return effect;
}
@@ -146,6 +193,10 @@ public class ${table.serviceImplName} implements ${table.serviceName} {
log.info("${type}Service-batchDelete${type}ByIdList idList: {}", idList);
int effect = ${typeLower}DAO.deleteBatchIds(idList);
log.info("${type}Service-batchDelete${type}ByIdList effect: {}", effect);
#if($cacheMeta.enableCache)
// 删除缓存
RedisMaps.delete(${type}CacheKeyDefine.${typeConst}, idList);
#end
return effect;
}
@@ -157,6 +208,10 @@ public class ${table.serviceImplName} implements ${table.serviceName} {
// 删除
int effect = ${typeLower}DAO.delete(wrapper);
log.info("${type}Service.delete${type} effect: {}", effect);
#if($cacheMeta.enableCache)
// 删除缓存
RedisMaps.delete(${type}CacheKeyDefine.${typeConst});
#end
return effect;
}

View File

@@ -52,7 +52,7 @@ public interface ${table.serviceName} {
${type}VO get${type}ById(Long id);
/**
* ${apiComment.listByIdList}
* ${apiComment.getByIdList}
*
* @param idList idList
* @return rows
@@ -60,13 +60,22 @@ public interface ${table.serviceName} {
List<${type}VO> get${type}ByIdList(List<Long> idList);
/**
* ${apiComment.listAll}
* ${apiComment.queryList}
*
* @param request request
* @return rows
*/
List<${type}VO> get${type}List(${type}QueryRequest request);
#if($cacheMeta.enableCache)
/**
* ${apiComment.queryListByCache}
*
* @return rows
*/
List<${type}VO> get${type}ListByCache();
#end
/**
* ${apiComment.queryCount}
*
@@ -92,7 +101,7 @@ public interface ${table.serviceName} {
Integer delete${type}ById(Long id);
/**
* ${apiComment.batchDeleteByIdList}
* ${apiComment.batchDelete}
*
* @param idList idList
* @return effect

View File

@@ -2,7 +2,7 @@ package ${currentPackage};
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.orion.lang.utils.collect.Collections;
import com.orion.lang.utils.collect.Lists;
import com.orion.ops.framework.common.constant.ErrorMessage;
import com.orion.ops.framework.common.utils.Valid;
#foreach($pkg in ${customModuleFilePackages})
@@ -19,7 +19,6 @@ import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
@@ -64,12 +63,9 @@ public class ${type}ApiImpl implements ${type}Api {
log.info("${type}Api.update${type} query: {}, update: {}", JSON.toJSONString(query), JSON.toJSONString(update));
Valid.valid(query);
Valid.valid(update);
// 条件
LambdaQueryWrapper<${type}DO> wrapper = this.buildQueryWrapper(query);
// 转换
${type}DO updateRecord = ${type}ProviderConvert.MAPPER.to(update);
// 更新
int effect = ${typeLower}DAO.update(updateRecord, wrapper);
int effect = ${typeLower}Service.update${type}(${type}ProviderConvert.MAPPER.toRequest(query),
${type}ProviderConvert.MAPPER.toRequest(update));
log.info("${type}Api.update${type} effect: {}", effect);
return effect;
}
@@ -88,9 +84,9 @@ public class ${type}ApiImpl implements ${type}Api {
}
@Override
public List<${type}DTO> get${type}ByIdList(Collection<Long> idList) {
public List<${type}DTO> get${type}ByIdList(List<Long> idList) {
log.info("${type}Api.get${type}ByIdList idList: {}", idList);
if (Collections.isEmpty(idList)) {
if (Lists.isEmpty(idList)) {
return new ArrayList<>();
}
// 查询
@@ -109,6 +105,14 @@ public class ${type}ApiImpl implements ${type}Api {
return ${typeLower}DAO.of(wrapper).list(${type}ProviderConvert.MAPPER::to);
}
@Override
public List<${type}DTO> get${type}ListByCache() {
return ${typeLower}Service.get${type}ListByCache()
.stream()
.map(${type}ProviderConvert.MAPPER::to)
.collect(Collectors.toList());
}
@Override
public Long get${type}Count(${type}QueryDTO dto) {
log.info("${type}Api.get${type}Count dto: {}", JSON.toJSONString(dto));
@@ -123,21 +127,18 @@ public class ${type}ApiImpl implements ${type}Api {
public Integer delete${type}ById(Long id) {
log.info("${type}Api.delete${type}ById id: {}", id);
Valid.notNull(id, ErrorMessage.ID_MISSING);
// 检查数据是否存在
${type}DO record = ${typeLower}DAO.selectById(id);
Valid.notNull(record, ErrorMessage.DATA_ABSENT);
// 删除
int effect = ${typeLower}DAO.deleteById(id);
log.info("${type}Api.delete${type}ById effect: {}", effect);
Integer effect = ${typeLower}Service.delete${type}ById(id);
log.info("${type}Api.delete${type}ById id: {}, effect: {}", id, effect);
return effect;
}
@Override
public Integer batchDelete${type}ByIdList(Collection<Long> idList) {
public Integer batchDelete${type}ByIdList(List<Long> idList) {
log.info("${type}Api.batchDelete${type}ByIdList idList: {}", idList);
Valid.notEmpty(idList, ErrorMessage.ID_MISSING);
// 删除
int effect = ${typeLower}DAO.deleteBatchIds(idList);
Integer effect = ${typeLower}Service.batchDelete${type}ByIdList(idList);
log.info("${type}Api.batchDelete${type}ByIdList effect: {}", effect);
return effect;
}
@@ -146,10 +147,8 @@ public class ${type}ApiImpl implements ${type}Api {
public Integer delete${type}(${type}QueryDTO dto) {
log.info("${type}Api.delete${type} dto: {}", JSON.toJSONString(dto));
Valid.valid(dto);
// 条件
LambdaQueryWrapper<${type}DO> wrapper = this.buildQueryWrapper(dto);
// 删除
int effect = ${typeLower}DAO.delete(wrapper);
Integer effect = ${typeLower}Service.delete${type}(${type}ProviderConvert.MAPPER.toRequest(dto));
log.info("${type}Api.delete${type} effect: {}", effect);
return effect;
}

View File

@@ -4,7 +4,6 @@ package ${currentPackage};
import ${pkg}.*;
#end
import java.util.Collection;
import java.util.List;
/**
@@ -50,21 +49,28 @@ public interface ${type}Api {
${type}DTO get${type}ById(Long id);
/**
* ${apiComment.listByIdList}
* ${apiComment.getByIdList}
*
* @param idList idList
* @return rows
*/
List<${type}DTO> get${type}ByIdList(Collection<Long> idList);
List<${type}DTO> get${type}ByIdList(List<Long> idList);
/**
* ${apiComment.listAll}
* ${apiComment.queryList}
*
* @param dto dto
* @return rows
*/
List<${type}DTO> get${type}List(${type}QueryDTO dto);
/**
* ${apiComment.queryListByCache}
*
* @return rows
*/
List<${type}DTO> get${type}ListByCache();
/**
* ${apiComment.queryCount}
*
@@ -82,12 +88,12 @@ public interface ${type}Api {
Integer delete${type}ById(Long id);
/**
* ${apiComment.batchDeleteByIdList}
* ${apiComment.batchDelete}
*
* @param idList idList
* @return effect
*/
Integer batchDelete${type}ByIdList(Collection<Long> idList);
Integer batchDelete${type}ByIdList(List<Long> idList);
/**
* ${apiComment.deleteAll}

View File

@@ -24,6 +24,8 @@ public interface ${type}ProviderConvert {
${type}ProviderConvert MAPPER = Mappers.getMapper(${type}ProviderConvert.class);
${type}DTO to(${type}VO dto);
${type}DO to(${type}DTO dto);
${type}DTO to(${type}DO domain);
@@ -32,12 +34,12 @@ public interface ${type}ProviderConvert {
${type}DO to(${type}UpdateDTO update);
${type}QueryRequest toRequest(${type}QueryDTO request);
${type}CreateRequest toRequest(${type}CreateDTO request);
${type}UpdateRequest toRequest(${type}UpdateDTO request);
List<${type}DTO> toList(List<${type}DO> list);
List<${type}DO> toList1(List<${type}DTO> list);
}

View File

@@ -110,5 +110,17 @@ public class ${type}ApiImplTests extends BaseUnitTest {
Integer effect = ${typeLower}Api.delete${type}(dto);
assertEquals(effect, 0);
}
#if($cacheMeta.enableCache)
// -------------------- cache --------------------
@Test
@Order(11)
public void get${type}ListByCacheTest() {
this.create${type}Test();
List<${type}DTO> list = ${typeLower}Api.get${type}ListByCache();
assertEquals(list.size(), 1);
}
#end
}

View File

@@ -121,5 +121,17 @@ public class ${type}ServiceImplTests extends BaseUnitTest {
Integer effect = ${typeLower}Service.delete${type}(query);
assertEquals(effect, 0);
}
#if($cacheMeta.enableCache)
// -------------------- cache --------------------
@Test
@Order(12)
public void get${type}ListByCacheTest() {
this.create${type}Test();
List<${type}VO> list = ${typeLower}Service.get${type}ListByCache();
assertEquals(list.size(), 1);
}
#end
}

View File

@@ -4,7 +4,7 @@
INSERT INTO system_menu
(parent_id, name, type, sort, visible, status, cache)
VALUES
(0, '${vue.comment}管理', 1, 10, 1, 1, 1);
(0, '${table.comment}管理', 1, 10, 1, 1, 1);
-- 设置临时父菜单id
SELECT @TMP_PARENT_ID:=LAST_INSERT_ID();
@@ -13,7 +13,7 @@ SELECT @TMP_PARENT_ID:=LAST_INSERT_ID();
INSERT INTO system_menu
(parent_id, name, type, sort, visible, status, cache, component)
VALUES
(@TMP_PARENT_ID, '$vue.comment', 2, 10, 1, 1, 1, '$vue.moduleEntityFirstLower$vue.featureEntity');
(@TMP_PARENT_ID, '$table.comment', 2, 10, 1, 1, 1, '$vue.moduleEntityFirstLower$vue.featureEntity');
-- 设置临时子菜单id
SELECT @TMP_SUB_ID:=LAST_INSERT_ID();
@@ -22,8 +22,8 @@ SELECT @TMP_SUB_ID:=LAST_INSERT_ID();
INSERT INTO system_menu
(parent_id, name, permission, type, sort)
VALUES
(@TMP_SUB_ID, '查询$vue.comment', '${package.ModuleName}:${typeHyphen}:query', 3, 10),
(@TMP_SUB_ID, '创建$vue.comment', '${package.ModuleName}:${typeHyphen}:create', 3, 20),
(@TMP_SUB_ID, '修改$vue.comment', '${package.ModuleName}:${typeHyphen}:update', 3, 30),
(@TMP_SUB_ID, '删除$vue.comment', '${package.ModuleName}:${typeHyphen}:delete', 3, 40),
(@TMP_SUB_ID, '导出$vue.comment', '${package.ModuleName}:${typeHyphen}:export', 3, 50);
(@TMP_SUB_ID, '查询$table.comment', '${package.ModuleName}:${typeHyphen}:query', 3, 10),
(@TMP_SUB_ID, '创建$table.comment', '${package.ModuleName}:${typeHyphen}:create', 3, 20),
(@TMP_SUB_ID, '修改$table.comment', '${package.ModuleName}:${typeHyphen}:update', 3, 30),
(@TMP_SUB_ID, '删除$table.comment', '${package.ModuleName}:${typeHyphen}:delete', 3, 40),
(@TMP_SUB_ID, '导出$table.comment', '${package.ModuleName}:${typeHyphen}:export', 3, 50);

View File

@@ -89,10 +89,10 @@ export function get${vue.featureEntity}(id: number) {
}
/**
* $apiComment.listByIdList
* $apiComment.getByIdList
*/
export function get${vue.featureEntity}List(idList: Array<number>) {
return axios.get<${vue.featureEntity}QueryResponse[]>('/${package.ModuleName}/${typeHyphen}/list', {
return axios.get<${vue.featureEntity}QueryResponse[]>('/${package.ModuleName}/${typeHyphen}/batch-get', {
params: { idList },
paramsSerializer: params => {
return qs.stringify(params, { arrayFormat: 'comma' });
@@ -101,10 +101,10 @@ export function get${vue.featureEntity}List(idList: Array<number>) {
}
/**
* $apiComment.listAll
* $apiComment.queryList
*/
export function get${vue.featureEntity}ListAll(request: ${vue.featureEntity}QueryRequest) {
return axios.post<Array<${vue.featureEntity}QueryResponse>>('/${package.ModuleName}/${typeHyphen}/list-all', request);
export function get${vue.featureEntity}List(request: ${vue.featureEntity}QueryRequest) {
return axios.post<Array<${vue.featureEntity}QueryResponse>>('/${package.ModuleName}/${typeHyphen}/list', request);
}
/**
@@ -122,10 +122,10 @@ export function delete${vue.featureEntity}(id: number) {
}
/**
* $apiComment.batchDeleteByIdList
* $apiComment.batchDelete
*/
export function batchDelete${vue.featureEntity}(idList: Array<number>) {
return axios.delete('/${package.ModuleName}/${typeHyphen}/delete-batch', {
return axios.delete('/${package.ModuleName}/${typeHyphen}/batch-delete', {
params: { idList },
paramsSerializer: params => {
return qs.stringify(params, { arrayFormat: 'comma' });