1.生成器工具类
package com.jmj.jpatemplate;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import com.jmj.jpatemplate.newService.*;
import com.jmj.jpatemplate.template.*;
import com.jmj.jpatemplate.valveService.ValveDaoTemplate;
import com.jmj.jpatemplate.valveService.ValveMvcControllerTemplate;
import com.jmj.jpatemplate.valveService.ValveServiceImplTemplate;
import com.jmj.jpatemplate.valveService.ValveServiceTemplate;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GenJPAUtils {
private static final String projectPath = System.getProperty("user.dir") + File.separator+"src"+File.separator+"main"+File.separator+"java"+File.separator;
private static final String basicPost = ".java";
private static final String controllerUrl = File.separator+"controller";
private static final String serviceUrl = File.separator+"service";
private static final String serviceImplUrl = File.separator+"service"+File.separator+"impl";
private static final String repositoryUrl = File.separator+"repository";
private static final String voUrl = File.separator+"vo";
private static final String dtoUrl = File.separator+"dto";
private static final String searchDtoUrl = dtoUrl+File.separator+"search";
private static final String entityUrl = File.separator+"entity";
private static final String feignUrl = File.separator+"client";
private static final String apiControllerUrl = File.separator+"controller";
private static final String bringUrl = File.separator+"service";
private static final String supplyServiceUrl = File.separator+"service";
private static final String supplyServiceImplUrl = File.separator+"service"+File.separator+"impl";
public static void main(String[] args) {
TemplateObj templateObj = new TemplateObj("com.jmj.jpatemplate.test",
"BlueParamTemplate", "蓝牙参数模板", "String","com.jmj.jpatemplate");
genCRUDNewServiceLatest(templateObj);
}
/**
* 生成最新JPA CRUD
* @param templateObj 模板参数
*/
public static void genCRUDNewServiceLatest(TemplateObj templateObj) {
Map<String, Object> tempMap = BeanUtil.beanToMap(templateObj);
String packageName = templateObj.getPackageName();
String relationUrl = projectPath + packageName.replace(".", File.separator);
// 创建controller
File touch = FileUtil.touch(relationUrl + controllerUrl + File.separator + templateObj.getControllerClass() + basicPost);
FileWriter controllerWriter = new FileWriter(touch, StandardCharsets.UTF_8);
controllerWriter.write(genTemplate(new NewControllerTemplate(), tempMap));
// 创建service
File touch1 = FileUtil.touch(relationUrl + serviceUrl + File.separator + templateObj.getServiceClass() + basicPost);
FileWriter serviceWriter = new FileWriter(touch1, StandardCharsets.UTF_8);
serviceWriter.write(genTemplate(new NewServiceTemplate(), tempMap));
// 创建serviceImpl
File touch2 = FileUtil.touch(relationUrl +serviceImplUrl + File.separator + templateObj.getServiceImplClass() + basicPost);
FileWriter serviceImplWriter = new FileWriter(touch2, StandardCharsets.UTF_8);
serviceImplWriter.write(genTemplate(new NewServiceImplTemplate(), tempMap));
// 创建Repository
File touch3 = FileUtil.touch(relationUrl + repositoryUrl + File.separator + templateObj.getDaoClass() + basicPost);
FileWriter repositoryWriter = new FileWriter(touch3, StandardCharsets.UTF_8);
repositoryWriter.write(genTemplate(new NewDaoTemplate(), tempMap));
// 创建searchDto
File touch4 = FileUtil.touch(relationUrl + searchDtoUrl + File.separator + templateObj.getSearchDtoClass() + basicPost);
FileWriter searchDtoWriter = new FileWriter(touch4, StandardCharsets.UTF_8);
searchDtoWriter.write(genTemplate(new NewSearchConditionDtoTemplate(), tempMap));
// 创建feignClient
File touch5 = FileUtil.touch(relationUrl + feignUrl + File.separator + templateObj.getFeignClass() + basicPost);
FileWriter feignWriter = new FileWriter(touch5, StandardCharsets.UTF_8);
feignWriter.write(genTemplate(new NewFeignTemplate(), tempMap));
// 创建forwardController
File touch6 = FileUtil.touch(relationUrl +feignUrl + File.separator + templateObj.getForwardControllerClass() + basicPost);
FileWriter forwardControllerWriter = new FileWriter(touch6, StandardCharsets.UTF_8);
forwardControllerWriter.write(genTemplate(new NewForwardControllerTemplate(), tempMap));
// 创建bring接口
File touch7 = FileUtil.touch(relationUrl +bringUrl + File.separator + templateObj.getBringClass() + basicPost);
FileWriter writer7 = new FileWriter(touch7, StandardCharsets.UTF_8);
writer7.write(genTemplate(new NewBringInterfaceTemplate(), tempMap));
// 创建supply接口
File touch8 = FileUtil.touch(relationUrl +supplyServiceUrl + File.separator + templateObj.getSupplyServiceClass() + basicPost);
FileWriter writer8 = new FileWriter(touch8, StandardCharsets.UTF_8);
writer8.write(genTemplate(new NewSupplyInterfaceTemplate(), tempMap));
// 创建supplyImpl实现类
File touch9 = FileUtil.touch(relationUrl +supplyServiceImplUrl + File.separator + templateObj.getSupplyServiceImplClass() + basicPost);
FileWriter writer9 = new FileWriter(touch9, StandardCharsets.UTF_8);
writer9.write(genTemplate(new NewSupplyServiceImplTemplate(), tempMap));
}
/**
* 生成ValveServer基本增删改查
* @param templateObj 模板参数
*/
public static void genCRUDValveServer(TemplateObj templateObj) {
Map<String, Object> tempMap = BeanUtil.beanToMap(templateObj);
String packageName = templateObj.getPackageName();
String relationUrl = projectPath + packageName.replace(".", File.separator);
// 创建controller
File touch = FileUtil.touch(relationUrl + controllerUrl + File.separator + templateObj.getControllerClass() + basicPost);
FileWriter controllerWriter = new FileWriter(touch, StandardCharsets.UTF_8);
controllerWriter.write(genTemplate(new ValveMvcControllerTemplate(), tempMap));
// 创建service
File touch1 = FileUtil.touch(relationUrl + serviceUrl + File.separator + templateObj.getServiceClass() + basicPost);
FileWriter serviceWriter = new FileWriter(touch1, StandardCharsets.UTF_8);
serviceWriter.write(genTemplate(new ValveServiceTemplate(), tempMap));
// 创建serviceImpl
File touch2 = FileUtil.touch(relationUrl +serviceImplUrl + File.separator + templateObj.getServiceImplClass() + basicPost);
FileWriter serviceImplWriter = new FileWriter(touch2, StandardCharsets.UTF_8);
serviceImplWriter.write(genTemplate(new ValveServiceImplTemplate(), tempMap));
// 创建Repository
File touch3 = FileUtil.touch(relationUrl + repositoryUrl + File.separator + templateObj.getDaoClass() + basicPost);
FileWriter repositoryWriter = new FileWriter(touch3, StandardCharsets.UTF_8);
repositoryWriter.write(genTemplate(new ValveDaoTemplate(), tempMap));
}
/**
* 生成基本增删改查
* @param templateObj 模板参数
*/
public static void genCRUD(TemplateObj templateObj) {
Map<String, Object> tempMap = BeanUtil.beanToMap(templateObj);
String packageName = templateObj.getPackageName();
String relationUrl = projectPath + packageName.replace(".", File.separator);
// 创建controller
File touch = FileUtil.touch(relationUrl + controllerUrl + File.separator + templateObj.getControllerClass() + basicPost);
FileWriter controllerWriter = new FileWriter(touch, StandardCharsets.UTF_8);
controllerWriter.write(genTemplate(new ControllerTemplate(), tempMap));
// 创建service
File touch1 = FileUtil.touch(relationUrl + serviceUrl + File.separator + templateObj.getServiceClass() + basicPost);
FileWriter serviceWriter = new FileWriter(touch1, StandardCharsets.UTF_8);
serviceWriter.write(genTemplate(new ServiceTemplate(), tempMap));
// 创建serviceImpl
File touch2 = FileUtil.touch(relationUrl + serviceImplUrl + File.separator + templateObj.getServiceImplClass() + basicPost);
FileWriter serviceImplWriter = new FileWriter(touch2, StandardCharsets.UTF_8);
serviceImplWriter.write(genTemplate(new ServiceImplTemplate(), tempMap));
// 创建Repository
File touch3 = FileUtil.touch(relationUrl + repositoryUrl + File.separator + templateObj.getDaoClass() + basicPost);
FileWriter repositoryWriter = new FileWriter(touch3, StandardCharsets.UTF_8);
repositoryWriter.write(genTemplate(new DaoTemplate(), tempMap));
// 创建vo
File touch4 = FileUtil.touch(relationUrl + voUrl + File.separator + templateObj.getEntityVoClass() + basicPost);
FileWriter voWriter = new FileWriter(touch4, StandardCharsets.UTF_8);
voWriter.write(genTemplate(new VoTemplate(), tempMap));
}
private static String replacePlaceholders(String input, Map<String, Object> placeholders) {
StringBuffer output = new StringBuffer();
// 正则匹配大括号内的内容 必须要有字符 {} 跳过直到下一个 }
// Pattern pattern = Pattern.compile("\\{(.+?)\\}");
// 正则匹配大括号内的内容 可以没有字符 {} 不跳过 匹配空串
Pattern pattern = Pattern.compile("\\{(.*?)\\}");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String key = matcher.group(1);
String replacement = placeholders.getOrDefault(key, "").toString();
if (!replacement.equals("")) {
matcher.appendReplacement(output, replacement);
}
}
matcher.appendTail(output);
return output.toString();
}
private static String genTemplate(BaseTemplate baseTemplate, Map<String, Object> tempMap) {
String template = baseTemplate.getTemplate();
return replacePlaceholders(template, tempMap);
}
/**
* 生成单个模板
* @param template 模板对象
* @param templateObj 模板参数
* @param absolutePath 绝对路径 不带斜杠
*/
public void genOneTemplate(BaseTemplate template,TemplateObj templateObj,String absolutePath){
Map<String, Object> tempMap = BeanUtil.beanToMap(templateObj);
String fileName;
if (template instanceof ControllerTemplate){
fileName = templateObj.getControllerClass() + basicPost;
}else if (template instanceof ServiceTemplate){
fileName = templateObj.getServiceClass() + basicPost;
}else if (template instanceof ServiceImplTemplate){
fileName = templateObj.getServiceImplClass() + basicPost;
}else if (template instanceof DaoTemplate){
fileName = templateObj.getDaoClass() + basicPost;
}else if (template instanceof VoTemplate){
fileName = templateObj.getEntityVoClass() + basicPost;
}else if (template instanceof FeignTemplate){
fileName = templateObj.getFeignClass() + basicPost;
}else if (template instanceof ValveServerControllerTemplate){
fileName = templateObj.getControllerApiClass() + basicPost;
}else {
throw new IllegalArgumentException("不支持该模板");
}
File touch = FileUtil.touch(absolutePath + File.separator + fileName);
FileWriter writer = new FileWriter(touch, StandardCharsets.UTF_8);
writer.write(genTemplate(new VoTemplate(), tempMap));
}
/**
* 用默认路径生成
* @param template 模板对象
* @param templateObj 模板参数
*/
public void genOneTemplate(BaseTemplate template,TemplateObj templateObj){
/**
* 到模块的包名为止
*/
String packageName = templateObj.getPackageName();
String relationUrl = projectPath + packageName.replace(".", File.separator);
String absolutePath;
//不带斜杠
if (template instanceof ControllerTemplate){
absolutePath = relationUrl + controllerUrl;
}else if (template instanceof ServiceTemplate){
absolutePath = relationUrl + serviceUrl;
}else if (template instanceof ServiceImplTemplate){
absolutePath = relationUrl + serviceImplUrl;
}else if (template instanceof DaoTemplate){
absolutePath = relationUrl + repositoryUrl;
}else if (template instanceof VoTemplate){
absolutePath = relationUrl + voUrl;
}else if (template instanceof FeignTemplate){
absolutePath = relationUrl + feignUrl;
}else if (template instanceof ValveServerControllerTemplate){
absolutePath = relationUrl + apiControllerUrl;
}else {
throw new IllegalArgumentException("不支持该模板");
}
genOneTemplate(template,templateObj,absolutePath);
}
}
2. controller模板
package com.jmj.jpatemplate.newService;
import com.jmj.jpatemplate.template.BaseTemplate;
public final class NewControllerTemplate extends BaseTemplate {
private final String template =
"""
package {packageName}.controller;
import com.x.globalcommonservice.global.exception.CodeException;
import com.x.globalcommonservice.global.validateGroup.AddGroup;
import com.x.globalcommonservice.global.validateGroup.UpdateGroup;
import com.x.globalcommonservice.global.vo.ResultVo;
import {packageName}.entity.{entityClass};
import {packageName}.service.{entityClass}Service;
import com.x.globalcommonservice.global.common.GlobalConst;
import {packageName}.dto.search.{entityClass}SearchConditionDto;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Set;
import java.util.List;
@Tag(name = "{entityChineseName}接口")
@RestController
@RequestMapping("/{entityName}")
public class {entityClass}Controller {
@Autowired
private {entityClass}Service {entityName}Service;
@ApiOperationSupport(author = "jmj",order = 1)
@Operation(summary = "添加{entityChineseName}")
@PostMapping("/add{entityClass}")
public ResultVo<Boolean> add{entityClass}(@Validated(AddGroup.class) @RequestBody {entityClass} {entityName}, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
{entityName}Service.add{entityClass}({entityName});
return new ResultVo<>(true);
}
@ApiOperationSupport(author = "jmj",order = 2)
@Operation(summary = "修改{entityChineseName}")
@PutMapping("/update{entityClass}")
public ResultVo<Boolean> update{entityClass}(@Validated(UpdateGroup.class) @RequestBody {entityClass} {entityName}, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
{entityName}Service.update{entityClass}({entityName});
return new ResultVo<>(true);
}
@ApiOperationSupport(author = "jmj",order = 3)
@Operation(summary = "查询{entityChineseName}")
@GetMapping("/findAll")
public ResultVo<List<{entityClass}>> findAll{entityClass}(@RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
List<{entityClass}> result = {entityName}Service.findAll{entityClass}();
return new ResultVo<>(result);
}
@ApiOperationSupport(author = "jmj", order = 4)
@Operation(summary = "条件分页查询{entityChineseName}")
@PostMapping("/findAllByPageCondition")
public ResultVo<Page<{entityClass}>> findAllByPageCondition(@RequestBody {entityClass}SearchConditionDto conditionDto,@RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
Page<{entityClass}> result = {entityName}Service.findAllByPageCondition(conditionDto);
return new ResultVo<>(result);
}
@ApiOperationSupport(author = "jmj",order = 5)
@Operation(summary = "根据ID查询{entityChineseName}")
@GetMapping("/findById/{id}")
public ResultVo<{entityClass}> find{entityClass}ById(@PathVariable("id") {idType} id, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
{entityClass} result = {entityName}Service.find{entityClass}ById(id);
return new ResultVo<>(result);
}
@ApiOperationSupport(author = "jmj",order = 6)
@Operation(summary = "根据ID删除{entityChineseName}")
@DeleteMapping("/deleteById/{id}")
public ResultVo<Boolean> delete{entityClass}ById(@PathVariable("id") {idType} id, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
{entityName}Service.delete{entityClass}ById(id);
return new ResultVo<>(true);
}
@ApiOperationSupport(author = "jmj",order = 7)
@Operation(summary = "根据IDs批量删除{entityChineseName}")
@DeleteMapping("/deleteByIds")
public ResultVo<Boolean> delete{entityClass}ByIds(@RequestBody Set<{idType}> ids, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
{entityName}Service.delete{entityClass}ByIds(ids);
return new ResultVo<>(true);
}
@ApiOperationSupport(author = "jmj",order = 8)
@Operation(summary = "根据复杂条件查询{entityChineseName}")
@PostMapping("/findByCondition")
public ResultVo<List<{entityClass}>> findByCondition(@RequestBody {entityClass}SearchConditionDto conditionDto,@RequestHeader(GlobalConst.X_USER_ID_HEADER)String requestAccountId) throws CodeException {
List<{entityClass}> result = {entityName}Service.findByCondition(conditionDto);
return new ResultVo<>(result);
}
}
""";
@Override
public String getTemplate() {
return template;
}
}
3.service模板
package com.jmj.jpatemplate.newService;
import com.jmj.jpatemplate.template.BaseTemplate;
public final class NewServiceTemplate extends BaseTemplate {
private final String template =
"""
package {packageName}.service;
import {packageName}.dto.search.{entityClass}SearchConditionDto;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.x.globalcommonservice.global.exception.CodeException;
import {packageName}.entity.{entityClass};
import org.springframework.data.domain.Page;
import java.util.Set;
import java.util.List;
/**
* {entityChineseName}业务层
*/
public interface {entityClass}Service {
/**
* 添加{entityChineseName}
* @param {entityName}
* @throws CodeException
*/
void add{entityClass}({entityClass} {entityName}) throws CodeException;
/**
* 修改{entityChineseName}
* @param {entityName}
* @throws CodeException
*/
void update{entityClass}({entityClass} {entityName}) throws CodeException;
/**
* 查询{entityChineseName}
* @return
*/
List<{entityClass}> findAll{entityClass}();
/**
* 查询分页
* @param conditionDto
* @return
*/
Page<{entityClass}> findAllByPageCondition({entityClass}SearchConditionDto conditionDto);
/**
* 根据ID查询{entityChineseName}
* @param id
* @return
*/
{entityClass} find{entityClass}ById({idType} id);
/**
* 根据ID删除{entityChineseName}
* @param id
*/
void delete{entityClass}ById({idType} id) throws CodeException ;
/**
* 批量删除{entityChineseName}
* @param ids
*/
void delete{entityClass}ByIds(Set<String> ids);
/**
* 根据复杂条件查询{entityChineseName}
*/
List<{entityClass}> findByCondition({entityClass}SearchConditionDto conditionDto) throws CodeException;
/**
* 根据对象获取booleanExpression
* @param conditionDto
* @return
*/
BooleanExpression getBooleanExpression({entityClass}SearchConditionDto conditionDto);
}
""";
@Override
public String getTemplate() {
return template;
}
}
4.serviceImpl模板
package com.jmj.jpatemplate.newService;
import com.jmj.jpatemplate.template.BaseTemplate;
public final class NewServiceImplTemplate extends BaseTemplate {
private final String template =
"""
package {packageName}.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import {packageName}.dto.search.{entityClass}SearchConditionDto;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.Expressions;
import com.x.globalcommonservice.global.utils.StringUtils;
import com.x.globalcommonservice.global.exception.CodeException;
import com.x.globalcommonservice.global.spring.abstractJPA.entity.AbstractJPABasicEntity;
import {packageName}.entity.{entityClass};
import {packageName}.entity.Q{entityClass};
import {packageName}.repository.{entityClass}Repository;
import {packageName}.service.{entityClass}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
/**
* {entityChineseName}业务层实现类
*/
@Service
public class {entityClass}ServiceImpl implements {entityClass}Service {
/**
* {entityChineseName}数据持久层
*/
@Autowired
private {entityClass}Repository {entityName}Repository;
/**
* 添加{entityChineseName}
* @param {entityName}
* @throws CodeException
*/
@Override
public void add{entityClass}({entityClass} {entityName}) throws CodeException {
if ({entityName}.getId()!=null) {
throw new CodeException(HttpStatus.BAD_REQUEST.value(),"ID必须为空");
}
{entityName}Repository.save({entityName});
}
/**
* 修改{entityChineseName}
* @param {entityName}
* @throws CodeException
*/
@Override
public void update{entityClass}({entityClass} {entityName}) throws CodeException {
String id = {entityName}.getId();
if (id==null) {
throw new CodeException(HttpStatus.BAD_REQUEST.value(),"ID不能为空");
}
{entityClass} databaseEntity = {entityName}Repository.findById(id).orElse(null);
if (databaseEntity==null){
throw new CodeException(HttpStatus.NOT_FOUND.value(),"未找到该条数据");
}
BeanUtil.copyProperties({entityName},databaseEntity , new CopyOptions().setIgnoreProperties(AbstractJPABasicEntity.PROPERTY_CREATE_TIME,AbstractJPABasicEntity.PROPERTY_CREATE_USER));
{entityName}Repository.save(databaseEntity);
}
/**
* 查询所有{entityChineseName}
* @return
*/
@Override
public List<{entityClass}> findAll{entityClass}() {
return {entityName}Repository.findAll();
}
/**
* 查询条件分页
* @param conditionDto
* @return
*/
@Override
public Page<{entityClass}> findAllByPageCondition({entityClass}SearchConditionDto conditionDto) {
Pageable pageable = conditionDto.initPageable();
BooleanExpression booleanExpression = getBooleanExpression(conditionDto);
return {entityName}Repository.findAll(booleanExpression, pageable);
}
/**
* 根据ID查询{entityChineseName}
* @param id
* @return
*/
@Override
public {entityClass} find{entityClass}ById({idType} id) {
return {entityName}Repository.findById(id).orElse(null);
}
/**
* 根据ID删除{entityChineseName}
* @param id
*/
@Override
public void delete{entityClass}ById({idType} id) throws CodeException {
{entityClass} {entityName} = {entityName}Repository.findById(id).orElse(null);
if ({entityName} == null) {
throw new CodeException(HttpStatus.NOT_FOUND.value(), "未找到该条数据");
}
{entityName}Repository.delete({entityName});
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete{entityClass}ByIds(Set<{idType}> ids) {
{entityName}Repository.deleteAllById(ids);
}
/**
* 根据复杂条件查询{entityChineseName}
* @param conditionDto
* @return
*/
@Override
public List<{entityClass}> findByCondition({entityClass}SearchConditionDto conditionDto) {
BooleanExpression expression = Expressions.TRUE;
BooleanExpression booleanExpression = getBooleanExpression(conditionDto);
if (booleanExpression == expression) {
return {entityName}Repository.findAll();
}
expression = booleanExpression;
return (List<{entityClass}>) {entityName}Repository.findAll(expression);
}
/**
* 根据对象获取booleanExpression
*
* @param conditionDto
* @return
*/
@Override
public BooleanExpression getBooleanExpression({entityClass}SearchConditionDto conditionDto) {
BooleanExpression expression = Expressions.TRUE;
if (conditionDto == null) {
return expression;
}
Q{entityClass} entity = Q{entityClass}.{entityName};
Set<{idType}> id = conditionDto.getId();
if (id != null && !id.isEmpty()) {
expression = expression.and(entity.id.in(id));
}
Set<{idType}> idNot = conditionDto.getIdNot();
if (idNot != null && !idNot.isEmpty()){
expression = expression.and(entity.id.notIn(idNot));
}
String key = conditionDto.getKey();
if (StringUtils.isNotBlank(key)) {
}
return expression;
}
}
""";
@Override
public String getTemplate() {
return template;
}
}
5.dao模板
package com.jmj.jpatemplate.newService;
import com.jmj.jpatemplate.template.BaseTemplate;
public final class NewDaoTemplate extends BaseTemplate {
private final String template = """
package {packageName}.repository;
import {packageName}.entity.{entityClass};
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
/**
* {entityChineseName} Repository持久层
*/
public interface {entityClass}Repository extends JpaRepository<{entityClass}, {idType}>, QuerydslPredicateExecutor<{entityClass}> {
}
""";
@Override
public String getTemplate() {
return template;
}
}
6.模板抽象类
package com.jmj.jpatemplate.template;
public abstract class BaseTemplate {
public abstract String getTemplate();
}
7.查询Dto模板
package com.jmj.jpatemplate.newService;
import com.jmj.jpatemplate.template.BaseTemplate;
public class NewSearchConditionDtoTemplate extends BaseTemplate {
private final String template = """
package {packageName}.dto.search;
import io.swagger.v3.oas.annotations.media.Schema;
import com.x.globalcommonservice.global.utils.PageHelper;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.util.Set;
/**
* {entityChineseName}搜索条件Dto
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Accessors(chain = true)
public class {entityClass}SearchConditionDto extends PageHelper {
@Schema(description = "关键字")
private String key;
@Schema(description = "主键")
private Set<{idType}> id;
@Schema(description = "主键not")
private Set<{idType}> idNot;
}
""";
@Override
public String getTemplate() {
return template;
}
}
8.Bring接口模板
package com.jmj.jpatemplate.newService;
import com.jmj.jpatemplate.template.BaseTemplate;
public final class NewBringInterfaceTemplate extends BaseTemplate {
private final String template = """
package {packageName}.service;
import {packageName}.entity.{entityClass};
/**
* 统一实现获取 {entityChineseName} 接口
*/
public interface {entityClass}Bring {
/**
* 获取 {entityChineseName} 信息
* @param {entityName} {entityChineseName}
*/
void bring{entityClass}({entityClass} {entityName});
/**
* 提供 {entityChineseName} id
* @return
*/
{idType} provide{entityClass}Id();
}
""";
@Override
public String getTemplate() {
return template;
}
}
9.supply接口
package com.jmj.jpatemplate.newService;
import com.jmj.jpatemplate.template.BaseTemplate;
public final class NewSupplyInterfaceTemplate extends BaseTemplate {
private final String template = """
package {packageName}.service;
import java.util.Collection;
/**
* 供给 {entityChineseName} 接口
*/
public interface {entityClass}SupplyService {
/**
* 供给 {entityChineseName} 信息
* @param collection 集合
* @param requestAccountId 用户请求ID
*/
void supply{entityClass}(Collection<? extends {entityClass}Bring> collection,String requestAccountId);
}
""";
@Override
public String getTemplate() {
return template;
}
}
10.supply实现类
package com.jmj.jpatemplate.newService;
import com.jmj.jpatemplate.template.BaseTemplate;
public final class NewSupplyServiceImplTemplate extends BaseTemplate {
private final String template = """
package {packageName}.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.x.globalcommonservice.global.vo.ResultVo;
import {packageName}.client.{entityClass}ServiceApiClient;
import com.x.globalcommonservice.global.utils.StringUtils;
import {packageName}.dto.search.{entityClass}SearchConditionDto;
import {packageName}.entity.{entityClass};
import {packageName}.service.{entityClass}Bring;
import {packageName}.service.{entityClass}SupplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 统一实现获取 {entityChineseName} 实现类
*/
@Slf4j
@Service
public class {entityClass}SupplyServiceImpl implements {entityClass}SupplyService {
/**
* api Client
*/
@Autowired
private {entityClass}ServiceApiClient {entityName}ServiceApiClient;
/**
* 供给 {entityChineseName} 信息
* @param collection 集合
* @param requestAccountId 用户请求ID
*/
@Override
public void supply{entityClass}(Collection<? extends {entityClass}Bring> collection, String requestAccountId) {
try {
if (CollectionUtil.isEmpty(collection)){
log.debug("{entityClass}SupplyServiceImpl.supply{entityClass}() 集合为空 collection:{}",collection);
return;
}
collection = collection.stream().filter(Objects::nonNull).collect(Collectors.toList());
if (CollectionUtil.isEmpty(collection)){
log.debug("{entityClass}SupplyServiceImpl.supply{entityClass}() 集合为空 collection:{}",collection);
return;
}
Set<{idType}> ids = collection
.stream()
.map({entityClass}Bring::provide{entityClass}Id)
.filter(StringUtils::isNotBlank).collect(Collectors.toSet());
ResultVo<List<{entityClass}>> byCondition = {entityName}ServiceApiClient.findByCondition(
new {entityClass}SearchConditionDto().setId(ids),
requestAccountId
);
if (!byCondition.isPresent()){
log.debug("{entityClass}SupplyServiceImpl.supply{entityClass}() 查询{entityChineseName}为空集");
return;
}
Map<String, {entityClass}> map = byCondition.getData()
.stream()
.collect(Collectors.toMap({entityClass}::getId, Function.identity()));
for ({entityClass}Bring {entityName}Bring : collection) {
try {
String id = {entityName}Bring.provide{entityClass}Id();
if (StringUtils.isBlank(id)){
log.debug("{entityClass}SupplyServiceImpl.supply{entityClass}() {entityChineseName}未绑定 entity={}",{entityName}Bring);
continue;
}
{entityClass} {entityName} = map.get(id);
if ({entityName}==null){
log.debug("{entityClass}SupplyServiceImpl.supply{entityClass}() {entityChineseName}不存在 entity={}",{entityName}Bring);
continue;
}
{entityName}Bring.bring{entityClass}({entityName});
} catch (Exception e) {
log.debug("{entityClass}SupplyServiceImpl.supply{entityClass}() 获取{entityChineseName}失败 entity={}",{entityName}Bring);
}
}
} catch (Exception e) {
log.error("{entityClass}SupplyServiceImpl.supply{entityClass}() 获取{entityChineseName}失败",e);
}
}
}
""";
@Override
public String getTemplate() {
return template;
}
}
11.Feign 模板
package com.jmj.jpatemplate.newService;
import com.jmj.jpatemplate.template.BaseTemplate;
public class NewFeignTemplate extends BaseTemplate {
private final String template = """
package {packageName}.client;
import com.x.globalcommonservice.global.common.GlobalConst;
import com.x.globalcommonservice.global.common.ServiceNameConst;
import com.x.globalcommonservice.global.validateGroup.AddGroup;
import com.x.globalcommonservice.global.validateGroup.UpdateGroup;
import com.x.globalcommonservice.global.vo.JPAPageVo;
import com.x.globalcommonservice.global.vo.ResultVo;
import com.x.globalcommonservice.model.productmanagerservice.common.ProductManagerConst;
import {packageName}.dto.search.{entityClass}SearchConditionDto;
import {packageName}.entity.{entityClass};
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Set;
/**
* {entityChineseName}接口
*/
@FeignClient(name = "{entityName}ServiceApiClient", path = ProductManagerConst.CONTEXT_PATH + "/{entityName}", url = "${" + ServiceNameConst.product_manage_service + ".url:http://192.168.202.57:10242}")
public interface {entityClass}ServiceApiClient {
@Operation(summary = "添加{entityChineseName}")
@PostMapping("/add{entityClass}")
public ResultVo<Boolean> add{entityClass}(@Validated(AddGroup.class) @RequestBody {entityClass} {entityName}, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId);
@Operation(summary = "修改{entityChineseName}")
@PutMapping("/update{entityClass}")
public ResultVo<Boolean> update{entityClass}(@Validated(UpdateGroup.class) @RequestBody {entityClass} {entityName}, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId);
@Operation(summary = "查询{entityChineseName}")
@GetMapping("/findAll")
public ResultVo<List<{entityClass}>> findAll{entityClass}(@RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId);
@Operation(summary = "条件分页查询{entityChineseName}")
@PostMapping("/findAllByPageCondition")
public ResultVo<JPAPageVo<{entityClass}>> findAllByPageCondition(@RequestBody {entityClass}SearchConditionDto conditionDto,@RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId);
@Operation(summary = "根据ID查询{entityChineseName}")
@GetMapping("/findById/{id}")
public ResultVo<{entityClass}> find{entityClass}ById(@PathVariable("id") {idType} id, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId);
@Operation(summary = "根据ID删除{entityChineseName}")
@DeleteMapping("/deleteById/{id}")
public ResultVo<Boolean> delete{entityClass}ById(@PathVariable("id") {idType} id, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId);
@Operation(summary = "根据IDs批量删除{entityChineseName}")
@DeleteMapping("/deleteByIds")
public ResultVo<Boolean> delete{entityClass}ByIds(@RequestBody Set<{idType}> ids, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId);
@Operation(summary = "根据复杂条件查询{entityChineseName}")
@PostMapping("/findByCondition")
public ResultVo<List<{entityClass}>> findByCondition(@RequestBody {entityClass}SearchConditionDto conditionDto,@RequestHeader(GlobalConst.X_USER_ID_HEADER)String requestAccountId) ;
}
""";
@Override
public String getTemplate() {
return template;
}
}
12.ForwardController
package com.jmj.jpatemplate.newService;
import com.jmj.jpatemplate.template.BaseTemplate;
public final class NewForwardControllerTemplate extends BaseTemplate {
private final String template =
"""
package {packageName}.controller;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.x.globalcommonservice.global.common.GlobalConst;
import com.x.globalcommonservice.global.exception.CodeException;
import com.x.globalcommonservice.global.validateGroup.AddGroup;
import com.x.globalcommonservice.global.validateGroup.UpdateGroup;
import com.x.globalcommonservice.global.vo.JPAPageVo;
import com.x.globalcommonservice.global.vo.ResultVo;
import {packageName}.client.{entityClass}ServiceApiClient;
import {packageName}.dto.search.{entityClass}SearchConditionDto;
import {packageName}.entity.{entityClass};
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Set;
@Tag(name = "{entityChineseName}Api接口")
@RestController
@RequestMapping("/manage-platform-service/v1/product-manager/{entityName}")
public class {entityClass}ForwardController {
@Autowired
private {entityClass}ServiceApiClient {entityName}ServiceApiClient;
@ApiOperationSupport(author = "jmj",order = 1)
@Operation(summary = "添加{entityChineseName}")
@PostMapping("/add{entityClass}")
public ResultVo<Boolean> add{entityClass}(@Validated(AddGroup.class) @RequestBody {entityClass} {entityName}, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
return {entityName}ServiceApiClient.add{entityClass}({entityName},requestAccountId);
}
@ApiOperationSupport(author = "jmj",order = 2)
@Operation(summary = "修改{entityChineseName}")
@PutMapping("/update{entityClass}")
public ResultVo<Boolean> update{entityClass}(@Validated(UpdateGroup.class) @RequestBody {entityClass} {entityName}, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
return {entityName}ServiceApiClient.update{entityClass}({entityName},requestAccountId);
}
@ApiOperationSupport(author = "jmj",order = 3)
@Operation(summary = "查询{entityChineseName}")
@GetMapping("/findAll")
public ResultVo<List<{entityClass}>> findAll{entityClass}(@RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
return {entityName}ServiceApiClient.findAll{entityClass}(requestAccountId);
}
@ApiOperationSupport(author = "jmj", order = 4)
@Operation(summary = "条件分页查询{entityChineseName}")
@PostMapping("/findAllByPageCondition")
public ResultVo<JPAPageVo<{entityClass}>> findAllByPageCondition(@RequestBody {entityClass}SearchConditionDto conditionDto,@RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
return {entityName}ServiceApiClient.findAllByPageCondition(conditionDto,requestAccountId);
}
@ApiOperationSupport(author = "jmj",order = 5)
@Operation(summary = "根据ID查询{entityChineseName}")
@GetMapping("/findById/{id}")
public ResultVo<{entityClass}> find{entityClass}ById(@PathVariable("id") {idType} id, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
return {entityName}ServiceApiClient.find{entityClass}ById(id,requestAccountId);
}
@ApiOperationSupport(author = "jmj",order = 6)
@Operation(summary = "根据ID删除{entityChineseName}")
@DeleteMapping("/deleteById/{id}")
public ResultVo<Boolean> delete{entityClass}ById(@PathVariable("id") {idType} id, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
return {entityName}ServiceApiClient.delete{entityClass}ById(id,requestAccountId);
}
@ApiOperationSupport(author = "jmj",order = 7)
@Operation(summary = "根据IDs批量删除{entityChineseName}")
@DeleteMapping("/deleteByIds")
public ResultVo<Boolean> delete{entityClass}ByIds(@RequestBody Set<{idType}> ids, @RequestHeader(GlobalConst.X_USER_ID_HEADER) String requestAccountId) throws CodeException {
return {entityName}ServiceApiClient.delete{entityClass}ByIds(ids,requestAccountId);
}
@ApiOperationSupport(author = "jmj",order = 8)
@Operation(summary = "根据复杂条件查询{entityChineseName}")
@PostMapping("/findByCondition")
public ResultVo<List<{entityClass}>> findByCondition(@RequestBody {entityClass}SearchConditionDto conditionDto,@RequestHeader(GlobalConst.X_USER_ID_HEADER)String requestAccountId) throws CodeException {
return {entityName}ServiceApiClient.findByCondition(conditionDto,requestAccountId);
}
}
""";
@Override
public String getTemplate() {
return template;
}
}