♻️ Refactoring code. pigx-codegen 适配最新V5 UI

This commit is contained in:
lbw committed 2023-04-06 15:03:58 +08:00
1 parent 3c047a59de
commit e6838a19e1
93 files changed
+3219 -2736

No files matched your search

-6
View File
@@ -146,12 +146,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 低代码 -->
<dependency>
<groupId>org.ssssssss</groupId>
<artifactId>magic-api-spring-boot-starter</artifactId>
<version>${magic.version}</version>
</dependency>
<!--undertow容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -1,58 +0,0 @@
package com.pig4cloud.pigx.codegen.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* magic 设计的接口鉴权处理逻辑
*
* @author lengleng
* @date 2022/7/12
*/
@ConditionalOnProperty("magic-api.prod")
@Configuration(proxyBeanMethods = false)
public class CustomDynamicApiAuthorizationInterceptor extends OncePerRequestFilter {
private final AntPathMatcher pathMatcher = new AntPathMatcher();
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
String requestURI = request.getRequestURI();
if (!pathMatcher.match("/api/dynamic/**", requestURI)) {
chain.doFilter(request, response);
return;
}
if (SecurityUtils.getAuthentication() == null) {
chain.doFilter(request, response);
return;
}
if (SecurityUtils.getAuthentication().getAuthorities().stream().map(GrantedAuthority::getAuthority)
.anyMatch(requestURI::contains)) {
chain.doFilter(request, response);
return;
}
response.setStatus(HttpStatus.FORBIDDEN.value());
response.getWriter().write(objectMapper.writeValueAsString(R.failed("权限不足,不允许访问")));
}
}
@@ -1,84 +0,0 @@
package com.pig4cloud.pigx.codegen.config;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
import org.ssssssss.magicapi.core.context.MagicUser;
import org.ssssssss.magicapi.core.interceptor.Authorization;
import org.ssssssss.magicapi.core.interceptor.AuthorizationInterceptor;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Enumeration;
/**
* magic 设计器鉴权处理
*
* @author lengleng
* @date 2022/7/10
*
* 自定义权限
*/
@RequiredArgsConstructor
@Configuration(proxyBeanMethods = false)
public class CustomMagicDesignerAuthorizationInterceptor implements AuthorizationInterceptor {
private final static String MAGIC_AUTHORITY = "gen_api_designer";
private final OpaqueTokenIntrospector opaqueTokenIntrospector;
/**
* 配置是否需要登录
*/
@Override
public boolean requireLogin() {
return true;
}
/**
* 是否拥有页面按钮的权限
*/
@Override
public boolean allowVisit(MagicUser magicUser, HttpServletRequest request, Authorization authorization) {
String accessToken = extractHeaderToken(request);
if (StrUtil.isBlank(accessToken)) {
throw new AccessDeniedException("权限不足");
}
OAuth2AuthenticatedPrincipal introspect = opaqueTokenIntrospector.introspect(accessToken);
Collection<? extends GrantedAuthority> authorities = introspect.getAuthorities();
// 查询权限
return authorities.stream().anyMatch(authority -> MAGIC_AUTHORITY.equals(authority.getAuthority()));
}
private String extractHeaderToken(HttpServletRequest request) {
Enumeration<String> headers = request.getHeaders(HttpHeaders.AUTHORIZATION);
while (headers.hasMoreElements()) { // typically there is only one (most servers
// enforce that)
String value = headers.nextElement();
if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
// Add this here for the auth details later. Would be better to change the
// signature of this method.
request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE,
value.substring(0, OAuth2AccessToken.BEARER_TYPE.length()).trim());
int commaIndex = authHeaderValue.indexOf(',');
if (commaIndex > 0) {
authHeaderValue = authHeaderValue.substring(0, commaIndex);
}
return authHeaderValue;
}
}
return null;
}
}
@@ -1,59 +0,0 @@
package com.pig4cloud.pigx.codegen.config;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.pig4cloud.pigx.common.core.factory.YamlPropertySourceFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.ssssssss.magicapi.core.interceptor.ResultProvider;
import org.ssssssss.magicapi.core.resource.DatabaseResource;
import org.ssssssss.magicapi.core.resource.Resource;
import org.ssssssss.magicapi.datasource.model.MagicDynamicDataSource;
import java.util.List;
/**
* 低代码设计相关
*
* @author lengleng
* @date 2022/5/20
*/
@RequiredArgsConstructor
@Configuration(proxyBeanMethods = false)
@PropertySource(value = "classpath:magic/magic.yml", factory = YamlPropertySourceFactory.class)
public class MagicApiConfiguration implements InitializingBean {
private final MagicDynamicDataSource magicDynamicDataSource;
private final List<DynamicDataSourceProvider> providers;
/**
* 定义 magic-api 存储
* @param jdbcTemplate
* @return 文件存储实现
*/
@Bean
public Resource databaseResource(JdbcTemplate jdbcTemplate) {
return new DatabaseResource(jdbcTemplate, "gen_api_file");
}
/**
* 格式化magic 结果输出
* @return
*/
@Bean
public ResultProvider resultProvider() {
return new RResultProvider();
}
@Override
public void afterPropertiesSet() {
for (DynamicDataSourceProvider provider : providers) {
provider.loadDataSources().forEach(magicDynamicDataSource::add);
}
}
}
@@ -1,41 +0,0 @@
package com.pig4cloud.pigx.codegen.config;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pig4cloud.pigx.common.core.util.R;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.interceptor.ResultProvider;
import org.ssssssss.magicapi.modules.db.model.Page;
import java.util.List;
import java.util.Map;
/**
* 返回R
*
* @author lengleng
* @date 2022/7/9
*/
public class RResultProvider implements ResultProvider {
@Override
public Object buildResult(RequestEntity requestEntity, int code, String message, Object data) {
return R.ok().setData(data).setMsg(message);
}
/**
* 定义分页返回结果,该项会被封装在Json结果内, 此方法可以不覆盖,默认返回PageResult
*/
@Override
public Object buildPageResult(RequestEntity requestEntity, Page page, long total, List<Map<String, Object>> data) {
IPage result = new com.baomidou.mybatisplus.extension.plugins.pagination.Page();
result.setTotal(total);
result.setRecords(data);
return R.ok(result);
}
@Override
public Object buildException(RequestEntity requestEntity, Throwable throwable) {
return R.failed(throwable.getLocalizedMessage());
}
}
@@ -16,17 +16,29 @@
*/
package com.pig4cloud.pigx.codegen.controller;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.smallbun.screw.boot.config.Screw;
import cn.smallbun.screw.boot.properties.ScrewProperties;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.GenDatasourceConf;
import com.pig4cloud.pigx.codegen.service.GenDatasourceConfService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.common.core.util.SpringContextHolder;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import com.pig4cloud.pigx.common.xss.core.XssCleanIgnore;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
/**
* 数据源管理
*
@@ -34,12 +46,14 @@ import org.springframework.web.bind.annotation.*;
* @date 2019-03-31 16:00:20
*/
@RestController
@AllArgsConstructor
@RequiredArgsConstructor
@RequestMapping("/dsconf")
public class GenDsConfController {
private final GenDatasourceConfService datasourceConfService;
private final Screw screw;
/**
* 分页查询
* @param page 分页对象
@@ -48,7 +62,9 @@ public class GenDsConfController {
*/
@GetMapping("/page")
public R getSysDatasourceConfPage(Page page, GenDatasourceConf datasourceConf) {
return R.ok(datasourceConfService.page(page, Wrappers.query(datasourceConf)));
return R.ok(datasourceConfService.page(page,
Wrappers.<GenDatasourceConf>lambdaQuery().like(StrUtil.isNotBlank(datasourceConf.getDsName()),
GenDatasourceConf::getDsName, datasourceConf.getDsName())));
}
/**
@@ -76,7 +92,6 @@ public class GenDsConfController {
* @param datasourceConf 数据源表
* @return R
*/
@SysLog("新增数据源表")
@PostMapping
@XssCleanIgnore
public R save(@RequestBody GenDatasourceConf datasourceConf) {
@@ -88,7 +103,6 @@ public class GenDsConfController {
* @param conf 数据源表
* @return R
*/
@SysLog("修改数据源表")
@PutMapping
@XssCleanIgnore
public R updateById(@RequestBody GenDatasourceConf conf) {
@@ -97,13 +111,35 @@ public class GenDsConfController {
/**
* 通过id删除数据源表
* @param id id
* @param ids id
* @return R
*/
@SysLog("删除数据源表")
@DeleteMapping("/{id}")
public R removeById(@PathVariable Long id) {
return R.ok(datasourceConfService.removeByDsId(id));
@DeleteMapping
public R removeById(@RequestBody Long[] ids) {
return R.ok(datasourceConfService.removeByDsId(ids));
}
/**
* 查询数据源对应的文档
* @param dsName 数据源名称
*/
@SneakyThrows
@GetMapping("/doc")
public void generatorDoc(String dsName, HttpServletResponse response) {
// 设置指定的数据源
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
DynamicDataSourceContextHolder.push(dsName);
DataSource dataSource = dynamicRoutingDataSource.determineDataSource();
// 设置指定的目标表
ScrewProperties screwProperties = SpringContextHolder.getBean(ScrewProperties.class);
// 生成
byte[] data = screw.documentGeneration(dataSource, screwProperties).toByteArray();
response.reset();
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType(ContentType.OCTET_STREAM.getValue());
IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
}
}
@@ -1,44 +0,0 @@
package com.pig4cloud.pigx.codegen.controller;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.service.GenDynamicService;
import com.pig4cloud.pigx.codegen.util.SqlDto;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import java.util.LinkedHashMap;
import java.util.List;
/**
* @author lengleng
* @date 2022/7/9
*
* 动态数据 无代码
*/
@RestController
@Inner(value = false)
@RequiredArgsConstructor
@RequestMapping("/dynamic")
@Tag(description = "dynamic", name = "无代码管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenDynamicController {
private final GenDynamicService dynamicService;
@GetMapping("/gen")
public R genCode(GenConfig genConfig) {
return R.ok(dynamicService.run(genConfig));
}
@PostMapping("/dynamic-query")
public R dynamicQuery(@RequestBody SqlDto sqlDto) {
List<LinkedHashMap<String, Object>> linkedHashMaps = dynamicService.dynamicQuery(sqlDto);
return R.ok(linkedHashMaps);
}
}
@@ -0,0 +1,136 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.controller;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.GenFieldType;
import com.pig4cloud.pigx.codegen.service.GenFieldTypeService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.excel.annotation.ResponseExcel;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 列属性
*
* @author pigx code generator
* @date 2023-02-06 20:16:01
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/fieldtype")
@Tag(description = "fieldtype", name = "列属性管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenFieldTypeController {
private final GenFieldTypeService fieldTypeService;
/**
* 分页查询
* @param page 分页对象
* @param fieldType 列属性
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
public R getFieldTypePage(Page page, GenFieldType fieldType) {
return R.ok(fieldTypeService.page(page,
Wrappers.<GenFieldType>lambdaQuery().like(StrUtil.isNotBlank(fieldType.getColumnType()),
GenFieldType::getColumnType, fieldType.getColumnType())));
}
@Operation(summary = "查询列表", description = "查询列表")
@GetMapping("/list")
public R list(GenFieldType fieldType) {
return R.ok(fieldTypeService.list(Wrappers.query(fieldType)));
}
/**
* 通过id查询列属性
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/details/{id}")
public R getById(@PathVariable("id") Long id) {
return R.ok(fieldTypeService.getById(id));
}
@GetMapping("/details")
public R getDetails(GenFieldType query) {
return R.ok(fieldTypeService.getOne(Wrappers.query(query), false));
}
/**
* 新增列属性
* @param fieldType 列属性
* @return R
*/
@Operation(summary = "新增列属性", description = "新增列属性")
@SysLog("新增列属性")
@PostMapping
public R save(@RequestBody GenFieldType fieldType) {
return R.ok(fieldTypeService.save(fieldType));
}
/**
* 修改列属性
* @param fieldType 列属性
* @return R
*/
@Operation(summary = "修改列属性", description = "修改列属性")
@SysLog("修改列属性")
@PutMapping
public R updateById(@RequestBody GenFieldType fieldType) {
return R.ok(fieldTypeService.updateById(fieldType));
}
/**
* 通过id删除列属性
* @param ids id
* @return R
*/
@Operation(summary = "通过id删除列属性", description = "通过id删除列属性")
@SysLog("通过id删除列属性")
@DeleteMapping
public R removeById(@RequestBody Long[] ids) {
return R.ok(fieldTypeService.removeBatchByIds(CollUtil.toList(ids)));
}
/**
* 导出excel 表格
* @param fieldType 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
public List<GenFieldType> export(GenFieldType fieldType) {
return fieldTypeService.list(Wrappers.query(fieldType));
}
}
@@ -17,20 +17,15 @@
package com.pig4cloud.pigx.codegen.controller;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import com.pig4cloud.pigx.codegen.service.GenFormConfService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
/**
@@ -40,10 +35,9 @@ import org.springframework.web.bind.annotation.*;
* @date 2019-08-12 15:55:35
*/
@RestController
@AllArgsConstructor
@RequiredArgsConstructor
@RequestMapping("/form")
@Tag(description = "form", name = "表单管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenFormConfController {
private final GenFormConfService genRecordService;
@@ -54,7 +48,7 @@ public class GenFormConfController {
* @param formConf 生成记录
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@Operation(description = "分页查询", summary = "分页查询")
@GetMapping("/page")
public R getGenFormConfPage(Page page, GenFormConf formConf) {
return R.ok(genRecordService.page(page, Wrappers.query(formConf)));
@@ -65,37 +59,22 @@ public class GenFormConfController {
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@Operation(description = "通过id查询", summary = "通过id查询")
@GetMapping("/{id}")
public R getById(@PathVariable("id") Long id) {
return R.ok(genRecordService.getById(id));
}
/**
* 通过id查询生成记录
* @param dsName 数据源ID
* @param tableName tableName
* @return R
*/
@Operation(summary = "通过tableName查询表单信息")
@Inner(value = false)
@GetMapping("/info")
public R form(String dsName, String tableName) {
return R.ok(genRecordService.getForm(dsName, tableName));
}
/**
* 新增生成记录
* @param formConf 生成记录
* @return R
*/
@Operation(summary = "新增生成记录", description = "新增生成记录")
@SysLog("新增生成记录")
@Operation(description = "新增生成记录", summary = "新增生成记录")
@PostMapping
@PreAuthorize("@pms.hasPermission('gen_form_add')")
public R save(@RequestBody GenFormConf formConf) {
formConf.setFormInfo(JSONUtil.toJsonPrettyStr(formConf.getFormInfo()));
return R.ok(genRecordService.save(formConf));
genRecordService.save(formConf);
return R.ok(formConf);
}
/**
@@ -103,10 +82,9 @@ public class GenFormConfController {
* @param formConf 生成记录
* @return R
*/
@Operation(summary = "修改生成记录", description = "修改生成记录")
@Operation(description = "修改生成记录", summary = "修改生成记录")
@SysLog("修改生成记录")
@PutMapping
@PreAuthorize("@pms.hasPermission('gen_form_edit')")
public R updateById(@RequestBody GenFormConf formConf) {
return R.ok(genRecordService.updateById(formConf));
}
@@ -116,10 +94,9 @@ public class GenFormConfController {
* @param id id
* @return R
*/
@Operation(summary = "通过id删除生成记录", description = "通过id删除生成记录")
@Operation(description = "通过id删除生成记录", summary = "通过id删除生成记录")
@SysLog("通过id删除生成记录")
@DeleteMapping("/{id}")
@PreAuthorize("@pms.hasPermission('gen_form_del')")
public R removeById(@PathVariable Long id) {
return R.ok(genRecordService.removeById(id));
}
@@ -0,0 +1,146 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.controller;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.GenGroupEntity;
import com.pig4cloud.pigx.codegen.util.vo.TemplateGroupDTO;
import com.pig4cloud.pigx.codegen.util.vo.GroupVo;
import com.pig4cloud.pigx.codegen.service.GenGroupService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.excel.annotation.ResponseExcel;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 模板分组
*
* @author PIG
* @date 2023-02-21 20:01:53
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/group")
@Tag(description = "group", name = "模板分组管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenGroupController {
private final GenGroupService genGroupService;
/**
* 分页查询
* @param page 分页对象
* @param genGroup 模板分组
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
@PreAuthorize("@pms.hasPermission('codegen_group_view')")
public R getgenGroupPage(Page page, GenGroupEntity genGroup) {
LambdaQueryWrapper<GenGroupEntity> wrapper = Wrappers.<GenGroupEntity>lambdaQuery()
.like(genGroup.getId() != null, GenGroupEntity::getId, genGroup.getId())
.like(StrUtil.isNotEmpty(genGroup.getGroupName()), GenGroupEntity::getGroupName,
genGroup.getGroupName());
return R.ok(genGroupService.page(page, wrapper));
}
/**
* 通过id查询模板分组
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
@PreAuthorize("@pms.hasPermission('codegen_group_view')")
public R getById(@PathVariable("id") Long id) {
return R.ok(genGroupService.getGroupVoById(id));
}
/**
* 新增模板分组
* @param genTemplateGroup 模板分组
* @return R
*/
@Operation(summary = "新增模板分组", description = "新增模板分组")
@SysLog("新增模板分组")
@PostMapping
@PreAuthorize("@pms.hasPermission('codegen_group_add')")
public R save(@RequestBody TemplateGroupDTO genTemplateGroup) {
genGroupService.saveGenGroup(genTemplateGroup);
return R.ok();
}
/**
* 修改模板分组
* @param groupVo 模板分组
* @return R
*/
@Operation(summary = "修改模板分组", description = "修改模板分组")
@SysLog("修改模板分组")
@PutMapping
@PreAuthorize("@pms.hasPermission('codegen_group_edit')")
public R updateById(@RequestBody GroupVo groupVo) {
genGroupService.updateGroupAndTemplateById(groupVo);
return R.ok();
}
/**
* 通过id删除模板分组
* @param ids id列表
* @return R
*/
@Operation(summary = "通过id删除模板分组", description = "通过id删除模板分组")
@SysLog("通过id删除模板分组")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('codegen_group_del')")
public R removeById(@RequestBody Long[] ids) {
genGroupService.delGroupAndTemplate(ids);
return R.ok();
}
/**
* 导出excel 表格
* @param genGroup 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
@PreAuthorize("@pms.hasPermission('codegen_group_export')")
public List<GenGroupEntity> export(GenGroupEntity genGroup) {
return genGroupService.list(Wrappers.query(genGroup));
}
@GetMapping("/list")
@Operation(summary = "查询列表", description = "查询列表")
public R list() {
List<GenGroupEntity> list = genGroupService.list();
return R.ok(list);
}
}
@@ -0,0 +1,165 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.GenTable;
import com.pig4cloud.pigx.codegen.entity.GenTableColumnEntity;
import com.pig4cloud.pigx.codegen.service.GenTableColumnService;
import com.pig4cloud.pigx.codegen.service.GenTableService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.excel.annotation.ResponseExcel;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 列属性
*
* @author pigx code generator
* @date 2023-02-06 20:34:55
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/table")
@Tag(description = "table", name = "列属性管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenTableController {
private final GenTableColumnService tableColumnService;
private final GenTableService tableService;
/**
* 分页查询
* @param page 分页对象
* @param table 列属性
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
public R getTablePage(Page page, GenTable table) {
return R.ok(tableService.list(page, table));
}
/**
* 通过id查询列属性
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
public R getById(@PathVariable("id") Long id) {
return R.ok(tableService.getById(id));
}
/**
* 新增列属性
* @param table 列属性
* @return R
*/
@Operation(summary = "新增列属性", description = "新增列属性")
@SysLog("新增列属性")
@PostMapping
public R save(@RequestBody GenTable table) {
return R.ok(tableService.save(table));
}
/**
* 修改列属性
* @param table 列属性
* @return R
*/
@Operation(summary = "修改列属性", description = "修改列属性")
@SysLog("修改列属性")
@PutMapping
public R updateById(@RequestBody GenTable table) {
return R.ok(tableService.updateById(table));
}
/**
* 通过id删除列属性
* @param id id
* @return R
*/
@Operation(summary = "通过id删除列属性", description = "通过id删除列属性")
@SysLog("通过id删除列属性")
@DeleteMapping("/{id}")
public R removeById(@PathVariable Long id) {
return R.ok(tableService.removeById(id));
}
/**
* 导出excel 表格
* @param table 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
public List<GenTable> export(GenTable table) {
return tableService.list(Wrappers.query(table));
}
/**
* 获取表信息
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/{dsName}/{tableName}")
public R<GenTable> info(@PathVariable("dsName") String dsName, @PathVariable String tableName) {
return R.ok(tableService.queryOrBuildTable(dsName, tableName));
}
/**
* 同步表信息
* @param dsName 数据源
* @param tableName 表名称
*/
@GetMapping("/sync/{dsName}/{tableName}")
public R<GenTable> sync(@PathVariable("dsName") String dsName, @PathVariable String tableName) {
// 表配置删除
tableService.remove(
Wrappers.<GenTable>lambdaQuery().eq(GenTable::getDsName, dsName).eq(GenTable::getTableName, tableName));
// 字段配置删除
tableColumnService.remove(Wrappers.<GenTableColumnEntity>lambdaQuery()
.eq(GenTableColumnEntity::getDsName, dsName).eq(GenTableColumnEntity::getTableName, tableName));
return R.ok(tableService.queryOrBuildTable(dsName, tableName));
}
/**
* 修改表字段数据
* @param dsName 数据源
* @param tableName 表名称
* @param tableFieldList 字段列表
*/
@PutMapping("/field/{dsName}/{tableName}")
public R<String> updateTableField(@PathVariable("dsName") String dsName, @PathVariable String tableName,
@RequestBody List<GenTableColumnEntity> tableFieldList) {
tableColumnService.updateTableField(dsName, tableName, tableFieldList);
return R.ok();
}
}
@@ -0,0 +1,149 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.controller;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.codegen.entity.GenTemplateEntity;
import com.pig4cloud.pigx.codegen.service.GenTemplateService;
import com.pig4cloud.pigx.common.xss.core.XssCleanIgnore;
import org.springframework.security.access.prepost.PreAuthorize;
import com.pig4cloud.pigx.common.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 模板
*
* @author PIG
* @date 2023-02-21 17:15:44
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/template")
@Tag(description = "template", name = "模板管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenTemplateController {
private final GenTemplateService genTemplateService;
/**
* 分页查询
* @param page 分页对象
* @param genTemplate 模板
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
@PreAuthorize("@pms.hasPermission('codegen_template_view')")
public R getgenTemplatePage(Page page, GenTemplateEntity genTemplate) {
LambdaQueryWrapper<GenTemplateEntity> wrapper = Wrappers.<GenTemplateEntity>lambdaQuery()
.like(genTemplate.getId() != null, GenTemplateEntity::getId, genTemplate.getId())
.like(StrUtil.isNotEmpty(genTemplate.getTemplateName()), GenTemplateEntity::getTemplateName,
genTemplate.getTemplateName());
return R.ok(genTemplateService.page(page, wrapper));
}
/**
* 查询全部模板
* @return
*/
@Operation(summary = "查询全部", description = "查询全部")
@GetMapping("/list")
@PreAuthorize("@pms.hasPermission('codegen_template_view')")
public R list() {
return R.ok(genTemplateService.list(Wrappers.emptyWrapper()));
}
/**
* 通过id查询模板
* @param id id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{id}")
@PreAuthorize("@pms.hasPermission('codegen_template_view')")
public R getById(@PathVariable("id") Long id) {
return R.ok(genTemplateService.getById(id));
}
/**
* 新增模板
* @param genTemplate 模板
* @return R
*/
@XssCleanIgnore
@Operation(summary = "新增模板", description = "新增模板")
@SysLog("新增模板")
@PostMapping
@PreAuthorize("@pms.hasPermission('codegen_template_add')")
public R save(@RequestBody GenTemplateEntity genTemplate) {
return R.ok(genTemplateService.save(genTemplate));
}
/**
* 修改模板
* @param genTemplate 模板
* @return R
*/
@XssCleanIgnore
@Operation(summary = "修改模板", description = "修改模板")
@SysLog("修改模板")
@PutMapping
@PreAuthorize("@pms.hasPermission('codegen_template_edit')")
public R updateById(@RequestBody GenTemplateEntity genTemplate) {
return R.ok(genTemplateService.updateById(genTemplate));
}
/**
* 通过id删除模板
* @param ids id列表
* @return R
*/
@Operation(summary = "通过id删除模板", description = "通过id删除模板")
@SysLog("通过id删除模板")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('codegen_template_del')")
public R removeById(@RequestBody Long[] ids) {
return R.ok(genTemplateService.removeBatchByIds(CollUtil.toList(ids)));
}
/**
* 导出excel 表格
* @param genTemplate 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
@PreAuthorize("@pms.hasPermission('codegen_template_export')")
public List<GenTemplateEntity> export(GenTemplateEntity genTemplate) {
return genTemplateService.list(Wrappers.query(genTemplate));
}
}
@@ -0,0 +1,131 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.controller;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.codegen.entity.GenTemplateGroupEntity;
import com.pig4cloud.pigx.codegen.service.GenTemplateGroupService;
import org.springframework.security.access.prepost.PreAuthorize;
import com.pig4cloud.pigx.common.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 模板分组关联表
*
* @author PIG
* @date 2023-02-22 09:25:15
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/templateGroup")
@Tag(description = "templateGroup", name = "模板分组关联表管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenTemplateGroupController {
private final GenTemplateGroupService genTemplateGroupService;
/**
* 分页查询
* @param page 分页对象
* @param genTemplateGroup 模板分组关联表
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page")
@PreAuthorize("@pms.hasPermission('codegen_templateGroup_view')")
public R getgenTemplateGroupPage(Page page, GenTemplateGroupEntity genTemplateGroup) {
LambdaQueryWrapper<GenTemplateGroupEntity> wrapper = Wrappers.lambdaQuery();
return R.ok(genTemplateGroupService.page(page, wrapper));
}
/**
* 通过id查询模板分组关联表
* @param groupId id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{groupId}")
@PreAuthorize("@pms.hasPermission('codegen_templateGroup_view')")
public R getById(@PathVariable("groupId") Long groupId) {
return R.ok(genTemplateGroupService.getById(groupId));
}
/**
* 新增模板分组关联表
* @param genTemplateGroup 模板分组关联表
* @return R
*/
@Operation(summary = "新增模板分组关联表", description = "新增模板分组关联表")
@SysLog("新增模板分组关联表")
@PostMapping
@PreAuthorize("@pms.hasPermission('codegen_templateGroup_add')")
public R save(@RequestBody GenTemplateGroupEntity genTemplateGroup) {
return R.ok(genTemplateGroupService.save(genTemplateGroup));
}
/**
* 修改模板分组关联表
* @param genTemplateGroup 模板分组关联表
* @return R
*/
@Operation(summary = "修改模板分组关联表", description = "修改模板分组关联表")
@SysLog("修改模板分组关联表")
@PutMapping
@PreAuthorize("@pms.hasPermission('codegen_templateGroup_edit')")
public R updateById(@RequestBody GenTemplateGroupEntity genTemplateGroup) {
return R.ok(genTemplateGroupService.updateById(genTemplateGroup));
}
/**
* 通过id删除模板分组关联表
* @param ids groupId列表
* @return R
*/
@Operation(summary = "通过id删除模板分组关联表", description = "通过id删除模板分组关联表")
@SysLog("通过id删除模板分组关联表")
@DeleteMapping
@PreAuthorize("@pms.hasPermission('codegen_templateGroup_del')")
public R removeById(@RequestBody Long[] ids) {
return R.ok(genTemplateGroupService.removeBatchByIds(CollUtil.toList(ids)));
}
/**
* 导出excel 表格
* @param genTemplateGroup 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
@PreAuthorize("@pms.hasPermission('codegen_templateGroup_export')")
public List<GenTemplateGroupEntity> export(GenTemplateGroupEntity genTemplateGroup) {
return genTemplateGroupService.list(Wrappers.query(genTemplateGroup));
}
}
@@ -17,25 +17,24 @@
package com.pig4cloud.pigx.codegen.controller;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.smallbun.screw.boot.config.Screw;
import cn.smallbun.screw.boot.properties.ScrewProperties;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.service.GenTableColumnService;
import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pigx.codegen.service.GeneratorService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.core.util.SpringContextHolder;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;
/**
* 代码生成器
@@ -44,83 +43,93 @@ import javax.sql.DataSource;
* @date 2018-07-30
*/
@RestController
@AllArgsConstructor
@RequiredArgsConstructor
@RequestMapping("/generator")
public class GeneratorController {
private final Screw screw;
private final GeneratorService generatorService;
private final GenTableColumnService columnService;
/**
* ZIP 下载生成代码
* @param tableIds 数据表ID
* @param response 流输出对象
*/
@SneakyThrows
@GetMapping("/download")
public void download(String tableIds, HttpServletResponse response) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
// 生成代码
for (String tableId : tableIds.split(StrUtil.COMMA)) {
generatorService.downloadCode(Long.parseLong(tableId), zip);
}
IoUtil.close(zip);
// zip压缩包数据
byte[] data = outputStream.toByteArray();
response.reset();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", tableIds));
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), false, data);
}
/**
* 列表
* @param tableName 参数集
* @param dsName 数据源编号
* @return 数据库表
* 目标目录生成代码
*/
@GetMapping("/page")
public R getPage(Page page, String tableName, String dsName) {
return R.ok(generatorService.getPage(page, tableName, dsName));
@ResponseBody
@GetMapping("/code")
public R<String> code(String tableIds) throws Exception {
// 生成代码
for (String tableId : tableIds.split(StrUtil.COMMA)) {
generatorService.generatorCode(Long.valueOf(tableId));
}
return R.ok();
}
/**
* 预览代码
* @param genConfig 数据表配置
* @param tableId 表ID
* @return
*/
@SneakyThrows
@GetMapping("/preview")
public R previewCode(GenConfig genConfig) {
return R.ok(generatorService.previewCode(genConfig));
public List<Map<String, String>> preview(Long tableId) {
return generatorService.preview(tableId);
}
/**
* 查询表的列信息
* @param page 分页
* @param genConfig 数据表配置
* @return
* 获取表单设计器初始化数据
* @param dsName 数据源名称
* @param tableName 表名称
* @return json string
*/
@GetMapping("/table")
public R getTable(Page page, GenConfig genConfig) {
return R.ok(columnService.listTable(page, genConfig));
@SneakyThrows
@GetMapping("/vform")
public String vform(String dsName, String tableName) {
return generatorService.vform(dsName, tableName);
}
/**
* 生成代码
* @param genConfig 数据表配置
* 获取表单设计器初始化数据
* @param formId 表单ID
* @return json string
*/
@SneakyThrows
@PostMapping("/code")
public void generatorCode(@RequestBody GenConfig genConfig, HttpServletResponse response) {
byte[] data = generatorService.generatorCode(genConfig);
@GetMapping("/vform/sfc")
public void vformSfc(Long formId, HttpServletResponse response) {
String result = generatorService.vformSfc(formId);
byte[] data = result.getBytes(StandardCharsets.UTF_8);
response.reset();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
String.format("attachment; filename=%s.zip", genConfig.getTableName()));
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=form.vue");
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
}
@SneakyThrows
@GetMapping("/doc")
public void generatorDoc(String[] tableNames, String dsName, HttpServletResponse response) {
// 设置指定的数据源
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
DynamicDataSourceContextHolder.push(dsName);
DataSource dataSource = dynamicRoutingDataSource.determineDataSource();
// 设置指定的目标表
ScrewProperties screwProperties = SpringContextHolder.getBean(ScrewProperties.class);
screwProperties.setDesignatedTableName(CollUtil.toList(tableNames));
// 生成
byte[] data = screw.documentGeneration(dataSource, screwProperties).toByteArray();
response.reset();
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
IoUtil.write(response.getOutputStream(), false, data);
}
}
@@ -0,0 +1,103 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 列属性
*
* @author pigx code generator
* @date 2023-02-06 20:16:01
*/
@Data
@TableName("gen_field_type")
@EqualsAndHashCode(callSuper = true)
@Schema(description = "列属性")
public class GenFieldType extends Model<GenFieldType> {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "id")
private Long id;
/**
* 字段类型
*/
@Schema(description = "字段类型")
private String columnType;
/**
* 属性类型
*/
@Schema(description = "属性类型")
private String attrType;
/**
* 属性包名
*/
@Schema(description = "属性包名")
private String packageName;
/**
* 创建人
*/
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建人")
private String createBy;
/**
* 修改人
*/
@TableField(fill = FieldFill.UPDATE)
@Schema(description = "修改人")
private String updateBy;
/**
* 创建时间
*/
@Schema(description = "创建时间")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 修改时间
*/
@Schema(description = "修改时间")
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime updateTime;
/**
* 删除标识(0-正常,1-删除)
*/
@TableLogic
@TableField(fill = FieldFill.INSERT)
@Schema(description = "删除标记,1:已删除,0:正常")
private String delFlag;
}
@@ -46,6 +46,12 @@ public class GenFormConf extends Model<GenFormConf> {
@Schema(description = "ID")
private Long id;
/**
* 数据源名称
*/
@Schema(description = "数据源名称")
private String dsName;
/**
* 表名称
*/
@@ -0,0 +1,98 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 模板分组
*
* @author PIG
* @date 2023-02-21 20:01:53
*/
@Data
@TableName("gen_group")
@EqualsAndHashCode(callSuper = true)
@Schema(description = "模板分组")
public class GenGroupEntity extends Model<GenGroupEntity> {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "id")
private Long id;
/**
* 分组名称
*/
@Schema(description = "分组名称")
private String groupName;
/**
* 分组描述
*/
@Schema(description = "分组描述")
@TableField(fill = FieldFill.INSERT)
private String groupDesc;
/**
* 创建人
*/
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建人")
private String createBy;
/**
* 修改人
*/
@TableField(fill = FieldFill.UPDATE)
@Schema(description = "修改人")
private String updateBy;
/**
* 创建时间
*/
@Schema(description = "创建时间")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 修改时间
*/
@Schema(description = "修改时间")
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime updateTime;
/**
* 删除标识(0-正常,1-删除)
*/
@TableLogic
@TableField(fill = FieldFill.INSERT)
@Schema(description = "删除标记,1:已删除,0:正常")
private String delFlag;
}
@@ -0,0 +1,172 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
import java.util.List;
/**
* 列属性
*
* @author pigx code generator
* @date 2023-02-06 20:34:55
*/
@Data
@TableName("gen_table")
@EqualsAndHashCode(callSuper = true)
@Schema(description = "列属性")
public class GenTable extends Model<GenTable> {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "id")
private Long id;
/**
* 数据源名称
*/
@Schema(description = "数据源名称")
private String dsName;
/**
* 数据源类型
*/
@Schema(description = "数据源类型")
private String dbType;
/**
* 表名
*/
@Schema(description = "表名")
private String tableName;
/**
* 类名
*/
@Schema(description = "类名")
private String className;
/**
* 说明
*/
@Schema(description = "说明")
private String tableComment;
/**
* 作者
*/
@Schema(description = "作者")
private String author;
/**
* 邮箱
*/
@Schema(description = "邮箱")
private String email;
/**
* 项目包名
*/
@Schema(description = "项目包名")
private String packageName;
/**
* 项目版本号
*/
@Schema(description = "项目版本号")
private String version;
/**
* 生成方式 0:zip压缩包 1:自定义目录
*/
@Schema(description = "生成方式 0:zip压缩包 1:自定义目录")
private Integer generatorType;
/**
* 后端生成路径
*/
@Schema(description = "后端生成路径")
private String backendPath;
/**
* 前端生成路径
*/
@Schema(description = "前端生成路径")
private String frontendPath;
/**
* 模块名
*/
@Schema(description = "模块名")
private String moduleName;
/**
* 功能名
*/
@Schema(description = "功能名")
private String functionName;
/**
* 表单布局 1:一列 2:两列
*/
@Schema(description = "表单布局 1:一列 2:两列")
private Integer formLayout;
/**
* 基类ID
*/
@Schema(description = "基类ID")
private Long baseclassId;
/**
* 创建时间
*/
@Schema(description = "创建时间")
private LocalDateTime createTime;
/**
* 代码生成风格
*/
private Long style;
/**
* 字段列表
*/
@TableField(exist = false)
private List<GenTableColumnEntity> fieldList;
/**
* 代码风格(模版分组信息)
*/
@TableField(exist = false)
private List<GenGroupEntity> groupList;
}
@@ -0,0 +1,155 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @author lengleng
* @date 2023-02-06
*
* 记录表字段的配置信息
*/
@Data
@TableName("gen_table_column")
@EqualsAndHashCode(callSuper = true)
public class GenTableColumnEntity extends Model<GenDatasourceConf> {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(type = IdType.ASSIGN_ID)
private Long id;
/**
* 数据源名
*/
private String dsName;
/**
* 表名称
*/
private String tableName;
/**
* 字段名称
*/
private String fieldName;
/**
* 排序
*/
private Integer sort;
/**
* 字段类型
*/
private String fieldType;
/**
* 字段说明
*/
private String fieldComment;
/**
* 属性名
*/
private String attrName;
/**
* 属性类型
*/
private String attrType;
/**
* 属性包名
*/
private String packageName;
/**
* 自动填充
*/
private String autoFill;
/**
* 主键 0:否 1:是
*/
private boolean primaryPk;
/**
* 基类字段 0:否 1:是
*/
private boolean baseField;
/**
* 表单项 0:否 1:是
*/
private boolean formItem;
/**
* 表单必填 0:否 1:是
*/
private boolean formRequired;
/**
* 表单类型
*/
private String formType;
/**
* 表单效验
*/
private String formValidator;
/**
* 列表项 0:否 1:是
*/
private boolean gridItem;
/**
* 列表排序 0:否 1:是
*/
private boolean gridSort;
/**
* 查询项 0:否 1:是
*/
private boolean queryItem;
/**
* 查询方式
*/
private String queryType;
/**
* 查询表单类型
*/
private String queryFormType;
/**
* 字段字典类型
*/
@TableField(updateStrategy = FieldStrategy.IGNORED)
private String fieldDict;
}
@@ -0,0 +1,109 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
/**
* 模板
*
* @author PIG
* @date 2023-02-21 17:15:44
*/
@Data
@TableName("gen_template")
@EqualsAndHashCode(callSuper = true)
@Schema(description = "模板")
public class GenTemplateEntity extends Model<GenTemplateEntity> {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "主键")
private Long id;
/**
* 模板名称
*/
@Schema(description = "模板名称")
private String templateName;
/**
* 模板路径
*/
@Schema(description = "模板路径")
private String generatorPath;
/**
* 模板描述
*/
@Schema(description = "模板描述")
private String templateDesc;
/**
* 模板代码
*/
@Schema(description = "模板代码")
private String templateCode;
/**
* 创建人
*/
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建人")
private String createBy;
/**
* 修改人
*/
@TableField(fill = FieldFill.UPDATE)
@Schema(description = "修改人")
private String updateBy;
/**
* 创建时间
*/
@Schema(description = "创建时间")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 修改时间
*/
@Schema(description = "修改时间")
@TableField(fill = FieldFill.UPDATE)
private LocalDateTime updateTime;
/**
* 删除标识(0-正常,1-删除)
*/
@TableLogic
@TableField(fill = FieldFill.INSERT)
@Schema(description = "删除标记,1:已删除,0:正常")
private String delFlag;
}
@@ -15,46 +15,42 @@
* Author: lengleng (wangiegie@gmail.com)
*/
package ${package}.${moduleName}.entity;
package com.pig4cloud.pigx.codegen.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
#if(${hasBigDecimal})
import java.math.BigDecimal;
#end
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* ${comments}
* 模板分组关联表
*
* @author ${author}
* @date ${datetime}
* @author PIG
* @date 2023-02-22 09:25:15
*/
@Data
@TableName("${tableName}")
@TableName("gen_template_group")
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
@Schema(description = "${comments}")
public class ${className} extends Model<${className}> {
@Schema(description = "模板分组关联表")
public class GenTemplateGroupEntity extends Model<GenTemplateGroupEntity> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
#foreach ($column in $columns)
/**
* $column.comments
*/
#if($column.columnName == $pk.columnName)
@TableId(type = IdType.ASSIGN_ID)
#end
#if($column.columnName == 'del_flag')
@TableLogic
#end
@Schema(description="$column.comments"#if($column.hidden),hidden=$column.hidden#end)
private $column.attrType $column.lowerAttrName;
/**
* 分组id
*/
@Schema(description = "分组id")
private Long groupId;
/**
* 模板id
*/
@Schema(description = "模板id")
private Long templateId;
#end
}
@@ -0,0 +1,44 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.mapper;
import com.pig4cloud.pigx.codegen.entity.GenFieldType;
import com.pig4cloud.pigx.common.data.datascope.PigxBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Set;
/**
* 列属性
*
* @author pigx code generator
* @date 2023-02-06 20:16:01
*/
@Mapper
public interface GenFieldTypeMapper extends PigxBaseMapper<GenFieldType> {
/**
* 根据tableId,获取包列表
* @param dsName 数据源名称
* @param tableName 表名称
* @return 返回包列表
*/
Set<String> getPackageByTableId(@Param("dsName") String dsName, @Param("tableName") String tableName);
}
@@ -0,0 +1,37 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.mapper;
import com.pig4cloud.pigx.codegen.util.vo.GroupVo;
import com.pig4cloud.pigx.common.data.datascope.PigxBaseMapper;
import com.pig4cloud.pigx.codegen.entity.GenGroupEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* 模板分组
*
* @author PIG
* @date 2023-02-21 20:01:53
*/
@Mapper
public interface GenGroupMapper extends PigxBaseMapper<GenGroupEntity> {
GroupVo getGroupVoById(@Param("id") Long id);
}
@@ -0,0 +1,33 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.mapper;
import com.pig4cloud.pigx.codegen.entity.GenTableColumnEntity;
import com.pig4cloud.pigx.common.data.datascope.PigxBaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 列属性
*
* @author pigx code generator
* @date 2023-02-06 20:16:01
*/
@Mapper
public interface GenTableColumnMapper extends PigxBaseMapper<GenTableColumnEntity> {
}
@@ -15,19 +15,19 @@
* Author: lengleng (wangiegie@gmail.com)
*/
package ${package}.${moduleName}.mapper;
package com.pig4cloud.pigx.codegen.mapper;
import com.pig4cloud.pigx.codegen.entity.GenTable;
import com.pig4cloud.pigx.common.data.datascope.PigxBaseMapper;
import ${package}.${moduleName}.entity.${className};
import org.apache.ibatis.annotations.Mapper;
/**
* ${comments}
* 列属性
*
* @author ${author}
* @date ${datetime}
* @author pigx code generator
* @date 2023-02-06 20:34:55
*/
@Mapper
public interface ${className}Mapper extends PigxBaseMapper<${className}> {
public interface GenTableMapper extends PigxBaseMapper<GenTable> {
}
@@ -0,0 +1,34 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pig4cloud.pigx.common.data.datascope.PigxBaseMapper;
import com.pig4cloud.pigx.codegen.entity.GenTemplateGroupEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 模板分组关联表
*
* @author PIG
* @date 2023-02-22 09:25:15
*/
@Mapper
public interface GenTemplateGroupMapper extends BaseMapper<GenTemplateGroupEntity> {
}
@@ -15,42 +15,28 @@
* Author: lengleng (wangiegie@gmail.com)
*/
import request from '@/router/axios'
package com.pig4cloud.pigx.codegen.mapper;
export function fetchList(query) {
return request({
url: '/${moduleName}/${pathName}/page',
method: 'get',
params: query
})
}
import com.pig4cloud.pigx.common.data.datascope.PigxBaseMapper;
import com.pig4cloud.pigx.codegen.entity.GenTemplateEntity;
import org.apache.ibatis.annotations.Mapper;
export function addObj(obj) {
return request({
url: '/${moduleName}/${pathName}',
method: 'post',
data: obj
})
}
import java.util.List;
export function getObj(id) {
return request({
url: '/${moduleName}/${pathName}/' + id,
method: 'get'
})
}
/**
* 模板
*
* @author PIG
* @date 2023-02-21 17:15:44
*/
@Mapper
public interface GenTemplateMapper extends PigxBaseMapper<GenTemplateEntity> {
export function delObj(id) {
return request({
url: '/${moduleName}/${pathName}/' + id,
method: 'delete'
})
}
/**
* 根据groupId查询 模板
* @param groupId
* @return
*/
List<GenTemplateEntity> listTemplateById(Long groupId);
export function putObj(obj) {
return request({
url: '/${moduleName}/${pathName}',
method: 'put',
data: obj
})
}
@@ -1,372 +0,0 @@
package com.pig4cloud.pigx.codegen.service;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pig4cloud.pigx.codegen.entity.*;
import com.pig4cloud.pigx.codegen.mapper.GenDatasourceConfMapper;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.core.exception.CheckedException;
import com.pig4cloud.pigx.common.core.util.SpringContextHolder;
import com.pig4cloud.pigx.common.datasource.util.DsJdbcUrlEnum;
import lombok.SneakyThrows;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.generic.DateTool;
import org.apache.velocity.tools.generic.MathTool;
import org.springframework.context.ApplicationContext;
import java.io.File;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 生成代码抽象
*
* @author lengleng
* @date 2022/7/11
*/
public interface GenCodeService {
default Map<String, Map> gen(GenConfig genConfig, Map<String, String> table, List<Map<String, String>> columns,
ZipOutputStream zip, GenFormConf formConf) {
// 构建表实体
TableEntity tableEntity = buildTableEntity(genConfig, table);
// 处理列相关
buildColumnEntity(tableEntity, columns);
// 模板入参
Map<String, Object> tempModel = buildTempModel(tableEntity, genConfig);
return renderData(genConfig, zip, tableEntity, tempModel, formConf);
}
/**
* 获取文件名
*/
default String getFileName(String template, String className, String packageName, String moduleName) {
String packagePath = CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main"
+ File.separator + "java" + File.separator;
if (StringUtils.isNotBlank(packageName)) {
packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
}
if (template.contains("Entity.java.vm")) {
return packagePath + "entity" + File.separator + className + ".java";
}
if (template.contains("Mapper.java.vm")) {
return packagePath + "mapper" + File.separator + className + "Mapper.java";
}
if (template.contains("Service.java.vm")) {
return packagePath + "service" + File.separator + className + "Service.java";
}
if (template.contains("ServiceImpl.java.vm")) {
return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
}
if (template.contains("Controller.java.vm")) {
return packagePath + "controller" + File.separator + className + "Controller.java";
}
if (template.contains("Mapper.xml.vm")) {
return CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main" + File.separator
+ "resources" + File.separator + "mapper" + File.separator + className + "Mapper.xml";
}
if (template.contains("menu.sql.vm")) {
return className.toLowerCase() + "_menu.sql";
}
return null;
}
/**
* 注入支持的模板列表
* @param config 用户输入
* @return ListString
*/
default List<String> getTemplates(GenConfig config) {
List<String> templates = new ArrayList<>();
templates.add("template/Entity.java.vm");
templates.add("template/Mapper.java.vm");
templates.add("template/Mapper.xml.vm");
templates.add("template/Service.java.vm");
templates.add("template/ServiceImpl.java.vm");
templates.add("template/Controller.java.vm");
templates.add("template/menu.sql.vm");
return templates;
}
/**
* 构建 TableEntity
* @param genConfig 用户输入相关
* @param table 表元信息
* @param columns 列元信息
* @param zip 输出zip流
* @param formConf 表单设计
* @return
*/
default TableEntity buildTableEntity(GenConfig genConfig, Map<String, String> table) {
// 表信息
TableEntity tableEntity = new TableEntity();
tableEntity.setTableName(table.get("tableName"));
if (StrUtil.isNotBlank(genConfig.getComments())) {
tableEntity.setComments(genConfig.getComments());
}
else {
tableEntity.setComments(table.get("tableComment"));
}
tableEntity.setDbType(table.get("dbType"));
String tablePrefix;
if (StrUtil.isNotBlank(genConfig.getTablePrefix())) {
tablePrefix = genConfig.getTablePrefix();
}
else {
tablePrefix = getConfig().getString("tablePrefix");
}
// 表名转换成Java类名
String className = tableToJava(tableEntity.getTableName(), tablePrefix);
tableEntity.setCaseClassName(className);
tableEntity.setLowerClassName(StringUtils.uncapitalize(className));
return tableEntity;
}
/**
* 构建 ColumnEntity
* @param columns 列元信息
* @return
*/
default void buildColumnEntity(TableEntity tableEntity, List<Map<String, String>> columns) {
List<Object> hiddenColumns = getConfig().getList("hiddenColumn");
// 列信息
List<ColumnEntity> columnList = new ArrayList<>();
for (Map<String, String> column : columns) {
ColumnEntity columnEntity = new ColumnEntity();
columnEntity.setColumnName(column.get("columnName"));
columnEntity.setDataType(column.get("dataType"));
columnEntity.setExtra(column.get("extra"));
columnEntity.setNullable("NO".equals(column.get("isNullable")));
columnEntity.setColumnType(column.get("columnType"));
// 隐藏不需要的在接口文档中展示的字段
if (hiddenColumns.contains(column.get("columnName"))) {
columnEntity.setHidden(Boolean.TRUE);
}
else {
columnEntity.setHidden(Boolean.FALSE);
}
// 列名转换成Java属性名
String attrName = columnToJava(columnEntity.getColumnName());
columnEntity.setCaseAttrName(attrName);
columnEntity.setLowerAttrName(StringUtils.uncapitalize(attrName));
// 判断注释是否为空
if (StrUtil.isNotBlank(column.get("comments"))) {
// 注意去除换行符号
columnEntity.setComments(StrUtil.removeAllLineBreaks(column.get("comments")));
}
else {
columnEntity.setComments(columnEntity.getLowerAttrName());
}
// 列的数据类型,转换成Java类型
String dataType = StrUtil.subBefore(columnEntity.getDataType(), "(", false);
String attrType = getConfig().getString(dataType, "unknowType");
columnEntity.setAttrType(attrType);
// 是否主键
if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) {
tableEntity.setPk(columnEntity);
}
columnList.add(columnEntity);
}
tableEntity.setColumns(columnList);
}
default Map<String, Object> buildTempModel(TableEntity tableEntity, GenConfig genConfig) {
// 封装模板数据
Map<String, Object> map = new HashMap<>(16);
map.put("dsName", genConfig.getDsName());
map.put("dbType", tableEntity.getDbType());
map.put("tableName", tableEntity.getTableName());
map.put("pk", tableEntity.getPk());
map.put("className", tableEntity.getCaseClassName());
map.put("classname", tableEntity.getLowerClassName());
map.put("pathName", tableEntity.getLowerClassName().toLowerCase());
map.put("columns", tableEntity.getColumns());
map.put("datetime", DateUtil.now());
if (StrUtil.isNotBlank(genConfig.getComments())) {
map.put("comments", genConfig.getComments());
}
else {
map.put("comments", tableEntity.getComments());
}
if (StrUtil.isNotBlank(genConfig.getAuthor())) {
map.put("author", genConfig.getAuthor());
}
else {
map.put("author", getConfig().getString("author"));
}
if (StrUtil.isNotBlank(genConfig.getModuleName())) {
map.put("moduleName", genConfig.getModuleName());
}
else {
map.put("moduleName", getConfig().getString("moduleName"));
}
if (StrUtil.isNotBlank(genConfig.getPackageName())) {
map.put("package", genConfig.getPackageName());
map.put("mainPath", genConfig.getPackageName());
}
else {
map.put("package", getConfig().getString("package"));
map.put("mainPath", getConfig().getString("mainPath"));
}
return map;
}
/**
* 渲染数据
* @param genConfig 用户输入相关
* @param zip 输出zip流
* @param tableEntity 表格实体
* @param map 参数集合
* @param formConf 表单设计
* @return
*/
@SneakyThrows
default Map<String, Map> renderData(GenConfig genConfig, ZipOutputStream zip, TableEntity tableEntity,
Map<String, Object> map, GenFormConf formConf) {
// 设置velocity资源加载器
Properties prop = new Properties();
prop.put("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(prop);
VelocityContext context = new VelocityContext(map);
// 函数库
context.put("math", new MathTool());
context.put("dateTool", new DateTool());
// 获取模板列表
List<String> templates = getTemplates(genConfig);
Map<String, Map> resultMap = new LinkedHashMap<>(8);
for (String template : templates) {
Map<String, String> templatesData = new HashMap<>();
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, CharsetUtil.UTF_8);
tpl.merge(context, sw);
// 添加到zip
String fileName = getFileName(template, tableEntity.getCaseClassName(), map.get("package").toString(),
map.get("moduleName").toString());
templatesData.put("codePath", fileName);
templatesData.put("code", sw.toString());
if (zip != null) {
try {
zip.putNextEntry(new ZipEntry(Objects.requireNonNull(fileName)));
IoUtil.write(zip, StandardCharsets.UTF_8, false, sw.toString());
IoUtil.close(sw);
}
catch (Exception e) {
}
}
resultMap.put(template, templatesData);
}
return resultMap;
}
/**
* 列名转换成Java属性名
*/
default String columnToJava(String columnName) {
return WordUtils.capitalizeFully(columnName, new char[] { '_' }).replace("_", "");
}
/**
* 表名转换成Java类名
*/
default String tableToJava(String tableName, String tablePrefix) {
if (StringUtils.isNotBlank(tablePrefix)) {
tableName = tableName.replaceFirst(tablePrefix, "");
}
return columnToJava(tableName);
}
/**
* 获取配置信息
*/
default Configuration getConfig() {
try {
return new PropertiesConfiguration("generator.properties");
}
catch (ConfigurationException e) {
throw new CheckedException("获取配置文件失败,", e);
}
}
/**
* 根据目标数据源名称动态匹配Mapper
* @param dsName
* @return
*/
default GeneratorMapper getMapper(String dsName) {
// 获取目标数据源数据库类型
GenDatasourceConfMapper datasourceConfMapper = SpringContextHolder.getBean(GenDatasourceConfMapper.class);
GenDatasourceConf datasourceConf = datasourceConfMapper
.selectOne(Wrappers.<GenDatasourceConf>lambdaQuery().eq(GenDatasourceConf::getName, dsName));
String dbConfType;
// 默认MYSQL 数据源
if (datasourceConf == null) {
dbConfType = DsJdbcUrlEnum.MYSQL.getDbName();
}
else {
dbConfType = datasourceConf.getDsType();
}
// 获取全部数据实现
ApplicationContext context = SpringContextHolder.getApplicationContext();
Map<String, GeneratorMapper> beansOfType = context.getBeansOfType(GeneratorMapper.class);
// 根据数据类型选择mapper
for (String key : beansOfType.keySet()) {
if (StrUtil.containsIgnoreCase(key, dbConfType)) {
return beansOfType.get(key);
}
}
throw new IllegalArgumentException("dsName 不合法: " + dsName);
}
}
@@ -57,9 +57,9 @@ public interface GenDatasourceConfService extends IService<GenDatasourceConf> {
/**
* 通过数据源名称删除
* @param dsId 数据源ID
* @param dsIds 数据源ID
* @return
*/
Boolean removeByDsId(Long dsId);
Boolean removeByDsId(Long[] dsIds);
}
@@ -1,29 +0,0 @@
package com.pig4cloud.pigx.codegen.service;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.util.SqlDto;
import java.util.LinkedHashMap;
import java.util.List;
/**
* @author lengleng
* @date 2022/7/9
*/
public interface GenDynamicService {
/**
* 执行代码
* @param genConfig 请求参数
* @return
*/
Object run(GenConfig genConfig);
/**
* 动态查询
* @param sqlDto 请求参数
* @return ListMap
*/
List<LinkedHashMap<String, Object>> dynamicQuery(SqlDto sqlDto);
}
@@ -0,0 +1,41 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pigx.codegen.entity.GenFieldType;
import java.util.Set;
/**
* 列属性
*
* @author pigx code generator
* @date 2023-02-06 20:16:01
*/
public interface GenFieldTypeService extends IService<GenFieldType> {
/**
* 根据tableId,获取包列表
* @param dsName 数据源名称
* @param tableName 表名称
* @return 返回包列表
*/
Set<String> getPackageByTableId(String dsName, String tableName);
}
@@ -17,9 +17,12 @@
package com.pig4cloud.pigx.codegen.service;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import java.util.List;
/**
* 表单管理
*
@@ -29,11 +32,10 @@ import com.pig4cloud.pigx.codegen.entity.GenFormConf;
public interface GenFormConfService extends IService<GenFormConf> {
/**
* 获取表单信息
* @param dsName 数据源ID
* @param tableName 表名称
* @return
* 解析 form json
* @param formInfo json
* @return 字段
*/
String getForm(String dsName, String tableName);
List<JSONObject> parse(String formInfo);
}
@@ -0,0 +1,53 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pigx.codegen.entity.GenGroupEntity;
import com.pig4cloud.pigx.codegen.util.vo.TemplateGroupDTO;
import com.pig4cloud.pigx.codegen.util.vo.GroupVo;
/**
* 模板分组
*
* @author PIG
* @date 2023-02-21 20:01:53
*/
public interface GenGroupService extends IService<GenGroupEntity> {
void saveGenGroup(TemplateGroupDTO genTemplateGroup);
/**
* 删除分组极其关系
* @param ids
*/
void delGroupAndTemplate(Long[] ids);
/**
* 查询group数据
* @param id
*/
GroupVo getGroupVoById(Long id);
/**
* 更新group数据
* @param groupVo
*/
void updateGroupAndTemplateById(GroupVo groupVo);
}
@@ -17,25 +17,21 @@
package com.pig4cloud.pigx.codegen.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.ColumnEntity;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pigx.codegen.entity.GenTableColumnEntity;
import java.util.List;
/**
* 表字段管理
* 列属性
*
* @author lengleng
* @date 2020-05-18
* @author pigx code generator
* @date 2023-02-06 20:16:01
*/
public interface GenTableColumnService {
public interface GenTableColumnService extends IService<GenTableColumnEntity> {
/**
* 查询表的字段信息
* @param page
* @param genConfig 查询条件
* @return
*/
IPage<ColumnEntity> listTable(Page page, GenConfig genConfig);
void initFieldList(List<GenTableColumnEntity> tableFieldList);
void updateTableField(String dsName, String tableName, List<GenTableColumnEntity> tableFieldList);
}
@@ -0,0 +1,46 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pigx.codegen.entity.GenTable;
import java.util.Map;
/**
* 列属性
*
* @author pigx code generator
* @date 2023-02-06 20:34:55
*/
public interface GenTableService extends IService<GenTable> {
/**
* 获取默认配置信息
* @param path 配置文件路径
* @return
*/
Map<String, Object> getGeneratorConfig(String path);
IPage list(Page<GenTable> page, GenTable table);
GenTable queryOrBuildTable(String dsName, String tableName);
}
@@ -0,0 +1,31 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pig4cloud.pigx.codegen.entity.GenTemplateGroupEntity;
/**
* 模板分组关联表
*
* @author PIG
* @date 2023-02-22 09:25:15
*/
public interface GenTemplateGroupService extends IService<GenTemplateGroupEntity> {
}
@@ -15,17 +15,17 @@
* Author: lengleng (wangiegie@gmail.com)
*/
package ${package}.${moduleName}.service;
package com.pig4cloud.pigx.codegen.service;
import com.baomidou.mybatisplus.extension.service.IService;
import ${package}.${moduleName}.entity.${className};
import com.pig4cloud.pigx.codegen.entity.GenTemplateEntity;
/**
* ${comments}
* 模板
*
* @author ${author}
* @date ${datetime}
* @author PIG
* @date 2023-02-21 17:15:44
*/
public interface ${className}Service extends IService<${className}> {
public interface GenTemplateService extends IService<GenTemplateEntity> {
}
@@ -17,11 +17,9 @@
package com.pig4cloud.pigx.codegen.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;
/**
* @author lengleng
@@ -30,26 +28,38 @@ import java.util.Map;
public interface GeneratorService {
/**
* 生成代码
* @param genConfig 生成信息
* @return
* 生成代码zip写出
* @param tableId 表
* @param zip 输出流
*/
byte[] generatorCode(GenConfig genConfig);
/**
* 分页查询表
* @param page 分页信息
* @param tableName 表名
* @param name 数据源ID
* @return
*/
IPage<Map<String, Object>> getPage(Page page, String tableName, String name);
void downloadCode(Long tableId, ZipOutputStream zip);
/**
* 预览代码
* @param genConfig 生成信息
* @return
* @param tableId 表
* @return [{模板名称:渲染结果}]
*/
Map<String, Map> previewCode(GenConfig genConfig);
List<Map<String, String>> preview(Long tableId);
/**
* 目标目录写入渲染结果
* @param tableId 表
*/
void generatorCode(Long tableId);
/**
* 获取表单设计器需要的 JSON
* @param dsName 数据源名称
* @param tableName 表名称
* @return json string
*/
String vform(String dsName, String tableName);
/**
* 获取表单设计器需要的 JSON
* @param formId 数据源名称
* @return json string
*/
String vformSfc(Long formId);
}
@@ -16,20 +16,20 @@
*/
package com.pig4cloud.pigx.codegen.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.druid.DruidConfig;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.codegen.config.MagicApiConfiguration;
import com.pig4cloud.pigx.codegen.entity.GenDatasourceConf;
import com.pig4cloud.pigx.codegen.mapper.GenDatasourceConfMapper;
import com.pig4cloud.pigx.codegen.service.GenDatasourceConfService;
import com.pig4cloud.pigx.common.core.util.SpringContextHolder;
import com.pig4cloud.pigx.common.datasource.util.DsConfTypeEnum;
import com.pig4cloud.pigx.common.datasource.util.DsJdbcUrlEnum;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.stereotype.Service;
@@ -47,7 +47,7 @@ import java.sql.SQLException;
*/
@Slf4j
@Service
@AllArgsConstructor
@RequiredArgsConstructor
public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfMapper, GenDatasourceConf>
implements GenDatasourceConfService {
@@ -55,8 +55,6 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
private final DataSourceCreator druidDataSourceCreator;
private MagicApiConfiguration apiConfiguration;
/**
* 保存数据源并且加密
* @param conf
@@ -75,9 +73,6 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
// 更新数据库配置
conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
this.baseMapper.insert(conf);
// 更新magic-api 数据源
apiConfiguration.afterPropertiesSet();
return Boolean.TRUE;
}
@@ -103,23 +98,20 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
conf.setPassword(stringEncryptor.encrypt(conf.getPassword()));
}
this.baseMapper.updateById(conf);
// 更新magic-api 数据源
apiConfiguration.afterPropertiesSet();
return Boolean.TRUE;
}
/**
* 通过数据源名称删除
* @param dsId 数据源ID
* @param dsIds 数据源ID
* @return
*/
@Override
public Boolean removeByDsId(Long dsId) {
public Boolean removeByDsId(Long[] dsIds) {
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
dynamicRoutingDataSource.removeDataSource(baseMapper.selectById(dsId).getName());
this.baseMapper.deleteById(dsId);
// 更新magic-api 数据源
apiConfiguration.afterPropertiesSet();
this.baseMapper.selectBatchIds(CollUtil.toList(dsIds))
.forEach(ds -> dynamicRoutingDataSource.removeDataSource(ds.getName()));
this.baseMapper.deleteBatchIds(CollUtil.toList(dsIds));
return Boolean.TRUE;
}
@@ -174,7 +166,7 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
}
catch (SQLException e) {
log.error("数据源配置 {} , 获取链接失败", conf.getName(), e);
return Boolean.FALSE;
throw new RuntimeException("数据库配置错误,链接失败");
}
return Boolean.TRUE;
}
@@ -1,150 +0,0 @@
package com.pig4cloud.pigx.codegen.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import com.pig4cloud.pigx.codegen.mapper.GenDynamicMapper;
import com.pig4cloud.pigx.codegen.mapper.GenFormConfMapper;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import com.pig4cloud.pigx.codegen.service.GenDynamicService;
import com.pig4cloud.pigx.codegen.util.SqlDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.ssssssss.magicapi.core.model.ApiInfo;
import org.ssssssss.magicapi.core.model.Group;
import org.ssssssss.magicapi.core.service.MagicResourceService;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 动态无代码实现类
*
* @author lengleng
* @date 2022/7/9
*/
@Service
@RequiredArgsConstructor
public class GenDynamicServiceImpl implements GenDynamicService {
private final MagicResourceService magicResourceService;
private final GenFormConfMapper genFormConfMapper;
private final GenDynamicMapper dynamicMapper;
private final GenCodeService magic;
/**
* 动态查询
* @param sqlDto 请求参数
* @return ListMap
*/
@Override
public List<LinkedHashMap<String, Object>> dynamicQuery(SqlDto sqlDto) {
DynamicDataSourceContextHolder.clear();
// 切换线程, 注意清空避免污染
DynamicDataSourceContextHolder.push(sqlDto.getDsName());
List<LinkedHashMap<String, Object>> linkedHashMaps = dynamicMapper.dynamicQuerySql(sqlDto.getSql());
DynamicDataSourceContextHolder.clear();
return linkedHashMaps;
}
@Override
public Map<String, Map> run(GenConfig genConfig) {
// 根据tableName 查询最新的表单配置
List<GenFormConf> formConfList = genFormConfMapper.selectList(Wrappers.<GenFormConf>lambdaQuery()
.eq(GenFormConf::getTableName, genConfig.getTableName()).orderByDesc(GenFormConf::getCreateTime));
String tableNames = genConfig.getTableName();
String dsName = genConfig.getDsName();
GeneratorMapper mapper = magic.getMapper(genConfig.getDsName());
Map<String, Map> templates = new HashMap<>();
for (String tableName : StrUtil.split(tableNames, StrUtil.DASHED)) {
// 查询表信息
Map<String, String> table = mapper.queryTable(tableName, dsName);
// 查询列信息
List<Map<String, String>> columns = mapper.selectMapTableColumn(tableName, dsName);
// 生成代码
if (CollUtil.isNotEmpty(formConfList)) {
templates = magic.gen(genConfig, table, columns, null, formConfList.get(0));
}
else {
templates = magic.gen(genConfig, table, columns, null, null);
}
// 分组
Group group = new Group();
String id = dsName + "_" + StrUtil.toSymbolCase(tableName, CharUtil.UNDERLINE);
group.setId(id);
group.setParentId("0");
group.setName(id);
group.setType("api");
group.setPath("/api/dynamic/" + dsName + "/" + StrUtil.toSymbolCase(tableName, CharUtil.UNDERLINE));
magicResourceService.saveGroup(group);
ApiInfo apiInfo = new ApiInfo();
apiInfo.setId(id + "_query");
Map<String, String> script = templates.get("template/magic/query.magic.vm");
apiInfo.setScript(script.get("code"));
apiInfo.setName("分页");
apiInfo.setPath("/list");
apiInfo.setMethod("post");
apiInfo.setGroupId(id);
magicResourceService.saveFile(apiInfo);
ApiInfo delApiInfo = new ApiInfo();
delApiInfo.setId(id + "_del");
Map<String, String> delScript = templates.get("template/magic/del.magic.vm");
delApiInfo.setScript(delScript.get("code"));
delApiInfo.setName("删除");
delApiInfo.setPath("/delete");
delApiInfo.setMethod("delete");
delApiInfo.setGroupId(id);
magicResourceService.saveFile(delApiInfo);
ApiInfo addApiInfo = new ApiInfo();
addApiInfo.setId(id + "_add");
Map<String, String> addScript = templates.get("template/magic/add.magic.vm");
addApiInfo.setScript(addScript.get("code"));
addApiInfo.setName("添加");
addApiInfo.setPath("/save");
addApiInfo.setMethod("post");
addApiInfo.setGroupId(id);
magicResourceService.saveFile(addApiInfo);
ApiInfo updateApiInfo = new ApiInfo();
updateApiInfo.setId(id + "_update");
Map<String, String> updateScript = templates.get("template/magic/update.magic.vm");
updateApiInfo.setScript(updateScript.get("code"));
updateApiInfo.setName("修改");
updateApiInfo.setPath("/update");
updateApiInfo.setMethod("put");
updateApiInfo.setGroupId(id);
magicResourceService.saveFile(updateApiInfo);
ApiInfo metadataApiInfo = new ApiInfo();
metadataApiInfo.setId(id + "metadata");
Map<String, String> metadataScript = templates.get("template/magic/metadata.magic.vm");
metadataApiInfo.setScript(metadataScript.get("code"));
metadataApiInfo.setName("元数据");
metadataApiInfo.setPath("/metadata");
metadataApiInfo.setMethod("get");
metadataApiInfo.setGroupId(id);
magicResourceService.saveFile(metadataApiInfo);
}
return templates;
}
}
@@ -0,0 +1,51 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.codegen.entity.GenFieldType;
import com.pig4cloud.pigx.codegen.mapper.GenFieldTypeMapper;
import com.pig4cloud.pigx.codegen.service.GenFieldTypeService;
import org.springframework.stereotype.Service;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 列属性
*
* @author pigx code generator
* @date 2023-02-06 20:16:01
*/
@Service
public class GenFieldTypeServiceImpl extends ServiceImpl<GenFieldTypeMapper, GenFieldType>
implements GenFieldTypeService {
/**
* 根据tableId,获取包列表
* @param dsName 数据源名称
* @param tableName 表名称
* @return 返回包列表
*/
@Override
public Set<String> getPackageByTableId(String dsName, String tableName) {
Set<String> importList = baseMapper.getPackageByTableId(dsName, tableName);
return importList.stream().filter(StrUtil::isNotBlank).collect(Collectors.toSet());
}
}
@@ -16,29 +16,17 @@
*/
package com.pig4cloud.pigx.codegen.service.impl;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.codegen.entity.ColumnEntity;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import com.pig4cloud.pigx.codegen.mapper.GenFormConfMapper;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import com.pig4cloud.pigx.codegen.service.GenFormConfService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.springframework.stereotype.Service;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Optional;
/**
* 表单管理
@@ -47,54 +35,33 @@ import java.util.Properties;
* @date 2019-08-12 15:55:35
*/
@Service
@AllArgsConstructor
public class GenFormConfServiceImpl extends ServiceImpl<GenFormConfMapper, GenFormConf> implements GenFormConfService {
private final GenCodeService avue;
/**
* 1. 根据数据源、表名称,查询已配置表单信息 2. 不存在调用模板生成
* @param dsName 数据源ID
* @param tableName 表名称
* @return
* 表单解析方法
* @param formInfo json
* @return 字段列表
*/
@Override
@SneakyThrows
public String getForm(String dsName, String tableName) {
GenFormConf form = getOne(Wrappers.<GenFormConf>lambdaQuery().eq(GenFormConf::getTableName, tableName)
.orderByDesc(GenFormConf::getCreateTime), false);
public List<JSONObject> parse(String formInfo) {
JSONObject jsonObject = JSONUtil.parseObj(formInfo);
List<JSONObject> objectList = new ArrayList<>();
// 使用 Lambda 表达式简化代码
Optional.ofNullable(jsonObject.getJSONArray("widgetList"))//
.ifPresent(widgetList -> widgetList.forEach(obj -> parseWidgetList((JSONObject) obj, objectList)));
return objectList;
}
if (form != null) {
return form.getFormInfo();
}
GeneratorMapper mapper = avue.getMapper(dsName);
List<ColumnEntity> columns = mapper.selectTableColumn(tableName, dsName);
// 设置velocity资源加载器
Properties prop = new Properties();
prop.put("resource.loader.file.class", ClasspathResourceLoader.class.getName());
Velocity.init(prop);
Template template = Velocity.getTemplate("template/avue/crud.js.vm", CharsetUtil.UTF_8);
VelocityContext context = new VelocityContext();
List<ColumnEntity> columnList = new ArrayList<>();
for (ColumnEntity column : columns) {
ColumnEntity columnEntity = new ColumnEntity();
columnEntity.setLowerAttrName(StringUtils.uncapitalize(avue.columnToJava(column.getColumnName())));
// 判断注释是否为空
if (StrUtil.isNotBlank(column.getComments())) {
columnEntity.setComments(column.getComments());
}
else {
columnEntity.setComments(columnEntity.getLowerAttrName());
}
columnList.add(columnEntity);
}
context.put("columns", columnList);
StringWriter writer = new StringWriter();
template.merge(context, writer);
return StrUtil.trim(StrUtil.removePrefix(writer.toString(), "export const tableOption ="));
/**
* 解析部件列表
* @param jsonObject 部件 json 对象
* @param objectList 对象列表
*/
private void parseWidgetList(JSONObject jsonObject, List<JSONObject> objectList) {
Optional.ofNullable(jsonObject.getJSONArray("cols"))//
.filter(cols -> !cols.isEmpty())//
.ifPresent(cols -> cols.forEach(colObj -> parseWidgetList((JSONObject) colObj, objectList)));
objectList.add(jsonObject);
}
}
@@ -0,0 +1,116 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.codegen.entity.GenGroupEntity;
import com.pig4cloud.pigx.codegen.entity.GenTemplateGroupEntity;
import com.pig4cloud.pigx.codegen.mapper.GenGroupMapper;
import com.pig4cloud.pigx.codegen.service.GenGroupService;
import com.pig4cloud.pigx.codegen.service.GenTemplateGroupService;
import com.pig4cloud.pigx.codegen.util.vo.GroupVo;
import com.pig4cloud.pigx.codegen.util.vo.TemplateGroupDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.LinkedList;
import java.util.List;
/**
* 模板分组
*
* @author PIG
* @date 2023-02-21 20:01:53
*/
@Slf4j
@Service
@AllArgsConstructor
public class GenGroupServiceImpl extends ServiceImpl<GenGroupMapper, GenGroupEntity> implements GenGroupService {
private final GenTemplateGroupService genTemplateGroupService;
/**
* 新增模板分组
* @param genTemplateGroup
*/
@Override
public void saveGenGroup(TemplateGroupDTO genTemplateGroup) {
// 1.保存group
GenGroupEntity groupEntity = new GenGroupEntity();
BeanUtil.copyProperties(genTemplateGroup, groupEntity);
baseMapper.insert(groupEntity);
// 2.保存关系
List<GenTemplateGroupEntity> goals = new LinkedList<>();
for (Long TemplateId : genTemplateGroup.getTemplateId()) {
GenTemplateGroupEntity templateGroup = new GenTemplateGroupEntity();
templateGroup.setTemplateId(TemplateId).setGroupId(groupEntity.getId());
goals.add(templateGroup);
}
genTemplateGroupService.saveBatch(goals);
}
/**
* 按照ids删除
* @param ids groupIds
*/
@Override
public void delGroupAndTemplate(Long[] ids) {
// 删除分组
this.removeBatchByIds(CollUtil.toList(ids));
// 删除关系
genTemplateGroupService
.remove(Wrappers.<GenTemplateGroupEntity>lambdaQuery().in(GenTemplateGroupEntity::getGroupId, ids));
}
/**
* 按照id查询
* @param id
* @return
*/
@Override
public GroupVo getGroupVoById(Long id) {
return baseMapper.getGroupVoById(id);
}
/**
* 根据id更新
* @param groupVo
*/
@Override
public void updateGroupAndTemplateById(GroupVo groupVo) {
// 1.更新自身
GenGroupEntity groupEntity = new GenGroupEntity();
BeanUtil.copyProperties(groupVo, groupEntity);
this.updateById(groupEntity);
// 2.更新模板
// 2.1根据id删除之前的模板
genTemplateGroupService.remove(
Wrappers.<GenTemplateGroupEntity>lambdaQuery().eq(GenTemplateGroupEntity::getGroupId, groupVo.getId()));
// 2.2根据ids创建新的模板分组赋值
List<GenTemplateGroupEntity> goals = new LinkedList<>();
for (Long templateId : groupVo.getTemplateId()) {
goals.add(new GenTemplateGroupEntity().setGroupId(groupVo.getId()).setTemplateId(templateId));
}
genTemplateGroupService.saveBatch(goals);
}
}
@@ -1,18 +1,23 @@
package com.pig4cloud.pigx.codegen.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.ColumnEntity;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import cn.hutool.core.text.NamingCase;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.codegen.entity.GenFieldType;
import com.pig4cloud.pigx.codegen.entity.GenTableColumnEntity;
import com.pig4cloud.pigx.codegen.mapper.GenFieldTypeMapper;
import com.pig4cloud.pigx.codegen.mapper.GenTableColumnMapper;
import com.pig4cloud.pigx.codegen.service.GenTableColumnService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* 表字段信息管理
*
@@ -21,29 +26,63 @@ import org.springframework.stereotype.Service;
*/
@Service
@RequiredArgsConstructor
public class GenTableColumnServiceImpl implements GenTableColumnService {
public class GenTableColumnServiceImpl extends ServiceImpl<GenTableColumnMapper, GenTableColumnEntity>
implements GenTableColumnService {
private final GenCodeService element;
private final GenFieldTypeMapper fieldTypeMapper;
@Override
public IPage<ColumnEntity> listTable(Page page, GenConfig genConfig) {
GeneratorMapper mapper = element.getMapper(genConfig.getDsName());
/**
* 初始化表单字段列表,主要是将数据库表中的字段转化为表单需要的字段数据格式,并为审计字段排序
* @param tableFieldList 表单字段列表
*/
public void initFieldList(List<GenTableColumnEntity> tableFieldList) {
// 字段类型、属性类型映射
List<GenFieldType> list = fieldTypeMapper.selectList(Wrappers.emptyWrapper());
Map<String, GenFieldType> fieldTypeMap = new LinkedHashMap<>(list.size());
list.forEach(
fieldTypeMapping -> fieldTypeMap.put(fieldTypeMapping.getColumnType().toLowerCase(), fieldTypeMapping));
// 关闭sql 优化
page.setOptimizeCountSql(false);
IPage<ColumnEntity> columnPage = mapper.selectTableColumn(page, genConfig.getTableName(),
genConfig.getDsName());
// 索引计数器
AtomicInteger index = new AtomicInteger(0);
tableFieldList.forEach(field -> {
// 将字段名转化为驼峰格式
field.setAttrName(NamingCase.toCamelCase(field.getFieldName()));
// 处理 数据库类型和 Java 类型关系
Configuration config = element.getConfig();
columnPage.getRecords().forEach(column -> {
// 只保留 ()之前部分,例如 timestamp(6) -> timestamp
String dataType = StrUtil.subBefore(column.getDataType(), "(", false);
String attrType = config.getString(dataType, "unknowType");
column.setLowerAttrName(StringUtils.uncapitalize(element.columnToJava(column.getColumnName())));
column.setJavaType(attrType);
// 获取字段对应的类型
GenFieldType fieldTypeMapping = fieldTypeMap.getOrDefault(field.getFieldType().toLowerCase(), null);
if (fieldTypeMapping == null) {
// 没找到对应的类型,则为Object类型
field.setAttrType("Object");
}
else {
field.setAttrType(fieldTypeMapping.getAttrType());
field.setPackageName(fieldTypeMapping.getPackageName());
}
// 设置查询类型和表单查询类型都为“=”
field.setQueryType("=");
field.setQueryFormType("text");
// 设置表单类型为文本框类型
field.setFormType("text");
// 保证审计字段最后显示
field.setSort(Objects.isNull(field.getSort()) ? index.getAndIncrement() : field.getSort());
});
return columnPage;
}
/**
* 更新指定数据源和表名的表单字段信息
* @param dsName 数据源名称
* @param tableName 表名
* @param tableFieldList 表单字段列表
*/
@Override
public void updateTableField(String dsName, String tableName, List<GenTableColumnEntity> tableFieldList) {
AtomicInteger sort = new AtomicInteger();
this.updateBatchById(tableFieldList.stream().peek(field -> field.setSort(sort.getAndIncrement()))
.collect(Collectors.toList()));
}
}
@@ -0,0 +1,189 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.service.impl;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.NamingCase;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.codegen.entity.GenGroupEntity;
import com.pig4cloud.pigx.codegen.entity.GenTable;
import com.pig4cloud.pigx.codegen.entity.GenTableColumnEntity;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.codegen.mapper.GenTableMapper;
import com.pig4cloud.pigx.codegen.service.GenGroupService;
import com.pig4cloud.pigx.codegen.service.GenTableColumnService;
import com.pig4cloud.pigx.codegen.service.GenTableService;
import com.pig4cloud.pigx.codegen.util.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* 列属性
*
* @author pigx code generator
* @date 2023-02-06 20:34:55
*/
@Service
@RequiredArgsConstructor
public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> implements GenTableService {
/**
* 默认配置信息
*/
private static final String CONFIG_PATH = "template/config.json";
private final GenTableColumnService columnService;
private final GenGroupService genGroupService;
/**
* 获取配置信息
* @param path 配置文件路径
* @return
*/
@Override
public Map<String, Object> getGeneratorConfig(String path) {
ClassPathResource classPathResource = new ClassPathResource(path);
JSONObject jsonObject = JSONUtil.parseObj(IoUtil.readUtf8(classPathResource.getStream()));
return jsonObject.getRaw();
}
@Override
public IPage list(Page<GenTable> page, GenTable table) {
GeneratorMapper mapper = GenKit.getMapper(table.getDsName());
// 手动切换数据源
DynamicDataSourceContextHolder.push(table.getDsName());
return mapper.queryTable(page, table.getTableName());
}
/**
* 获取表信息
* @param dsName
* @param tableName
* @return
*/
@Override
public GenTable queryOrBuildTable(String dsName, String tableName) {
GenTable genTable = baseMapper.selectOne(
Wrappers.<GenTable>lambdaQuery().eq(GenTable::getTableName, tableName).eq(GenTable::getDsName, dsName));
// 如果 genTable 为空, 执行导入
if (Objects.isNull(genTable)) {
genTable = this.tableImport(dsName, tableName);
}
List<GenTableColumnEntity> fieldList = columnService
.list(Wrappers.<GenTableColumnEntity>lambdaQuery().eq(GenTableColumnEntity::getDsName, dsName)
.eq(GenTableColumnEntity::getTableName, tableName).orderByAsc(GenTableColumnEntity::getSort));
genTable.setFieldList(fieldList);
// 查询模板分组信息
List<GenGroupEntity> groupEntities = genGroupService.list();
genTable.setGroupList(groupEntities);
return genTable;
}
@Transactional(rollbackFor = Exception.class)
public GenTable tableImport(String dsName, String tableName) {
GeneratorMapper mapper = GenKit.getMapper(dsName);
// 手动切换数据源
DynamicDataSourceContextHolder.push(dsName);
// 查询表是否存在
GenTable table = new GenTable();
// 从数据库获取表信息
Map<String, String> queryTable = mapper.queryTable(tableName, dsName);
// 获取默认表配置信息 ()
Map<String, Object> generatorConfig = getGeneratorConfig(CONFIG_PATH);
JSONObject project = (JSONObject) generatorConfig.get("project");
JSONObject developer = (JSONObject) generatorConfig.get("developer");
table.setPackageName(project.getStr("packageName"));
table.setVersion(project.getStr("version"));
table.setBackendPath(project.getStr("backendPath"));
table.setFrontendPath(project.getStr("frontendPath"));
table.setAuthor(developer.getStr("author"));
table.setEmail(developer.getStr("email"));
table.setTableName(tableName);
table.setDsName(dsName);
table.setTableComment(MapUtil.getStr(queryTable, "tableComment"));
table.setDbType(MapUtil.getStr(queryTable, "dbType"));
table.setFormLayout(FormLayoutEnum.ONE.getValue());
table.setGeneratorType(GeneratorTypeEnum.ZIP_DOWNLOAD.ordinal());
table.setClassName(NamingCase.toPascalCase(tableName));
table.setModuleName(GenKit.getModuleName(table.getPackageName()));
table.setFunctionName(GenKit.getFunctionName(tableName));
table.setCreateTime(LocalDateTime.now());
this.save(table);
// 获取原生字段数据
List<Map<String, String>> queryColumnList = mapper.selectMapTableColumn(tableName, dsName);
List<GenTableColumnEntity> tableFieldList = new ArrayList<>();
for (Map<String, String> columnMap : queryColumnList) {
String columnName = MapUtil.getStr(columnMap, "columnName");
GenTableColumnEntity genTableColumnEntity = new GenTableColumnEntity();
genTableColumnEntity.setTableName(tableName);
genTableColumnEntity.setDsName(dsName);
genTableColumnEntity.setFieldName(MapUtil.getStr(columnMap, "columnName"));
genTableColumnEntity.setFieldComment(MapUtil.getStr(columnMap, "comments"));
genTableColumnEntity.setFieldType(MapUtil.getStr(columnMap, "dataType"));
String columnKey = MapUtil.getStr(columnMap, "columnKey");
genTableColumnEntity.setPrimaryPk(StringUtils.isNotBlank(columnKey) && "PRI".equalsIgnoreCase(columnKey));
genTableColumnEntity.setAutoFill(AutoFillEnum.DEFAULT.name());
genTableColumnEntity.setFormItem(true);
genTableColumnEntity.setGridItem(true);
// 审计字段处理
if (EnumUtil.contains(CommonColumnFiledEnum.class, columnName)) {
CommonColumnFiledEnum commonColumnFiledEnum = CommonColumnFiledEnum.valueOf(columnName);
genTableColumnEntity.setFormItem(commonColumnFiledEnum.getFormItem());
genTableColumnEntity.setGridItem(commonColumnFiledEnum.getGridItem());
genTableColumnEntity.setAutoFill(commonColumnFiledEnum.getAutoFill());
genTableColumnEntity.setSort(commonColumnFiledEnum.getSort());
}
tableFieldList.add(genTableColumnEntity);
}
// 初始化字段数据
columnService.initFieldList(tableFieldList);
// 保存列数据
columnService.saveOrUpdateBatch(tableFieldList);
table.setFieldList(tableFieldList);
return table;
}
}
@@ -0,0 +1,35 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.codegen.entity.GenTemplateGroupEntity;
import com.pig4cloud.pigx.codegen.mapper.GenTemplateGroupMapper;
import com.pig4cloud.pigx.codegen.service.GenTemplateGroupService;
import org.springframework.stereotype.Service;
/**
* 模板分组关联表
*
* @author PIG
* @date 2023-02-22 09:25:15
*/
@Service
public class GenTemplateGroupServiceImpl extends ServiceImpl<GenTemplateGroupMapper, GenTemplateGroupEntity>
implements GenTemplateGroupService {
}
@@ -14,21 +14,22 @@
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package ${package}.${moduleName}.service.impl;
package com.pig4cloud.pigx.codegen.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ${package}.${moduleName}.entity.${className};
import ${package}.${moduleName}.mapper.${className}Mapper;
import ${package}.${moduleName}.service.${className}Service;
import com.pig4cloud.pigx.codegen.entity.GenTemplateEntity;
import com.pig4cloud.pigx.codegen.mapper.GenTemplateMapper;
import com.pig4cloud.pigx.codegen.service.GenTemplateService;
import org.springframework.stereotype.Service;
/**
* ${comments}
* 模板
*
* @author ${author}
* @date ${datetime}
* @author PIG
* @date 2023-02-21 11:08:43
*/
@Service
public class ${className}ServiceImpl extends ServiceImpl<${className}Mapper, ${className}> implements ${className}Service {
public class GenTemplateServiceImpl extends ServiceImpl<GenTemplateMapper, GenTemplateEntity>
implements GenTemplateService {
}
@@ -18,26 +18,28 @@
package com.pig4cloud.pigx.codegen.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import cn.hutool.json.JSONObject;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import com.pig4cloud.pigx.codegen.mapper.GenFormConfMapper;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import com.pig4cloud.pigx.codegen.service.GeneratorService;
import com.pig4cloud.pigx.common.core.constant.enums.StyleTypeEnum;
import lombok.AllArgsConstructor;
import com.pig4cloud.pigx.codegen.entity.GenTable;
import com.pig4cloud.pigx.codegen.entity.GenTableColumnEntity;
import com.pig4cloud.pigx.codegen.entity.GenTemplateEntity;
import com.pig4cloud.pigx.codegen.service.*;
import com.pig4cloud.pigx.codegen.util.GeneratorStyleEnum;
import com.pig4cloud.pigx.codegen.util.VelocityKit;
import com.pig4cloud.pigx.codegen.util.vo.GroupVo;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
@@ -46,96 +48,237 @@ import java.util.zip.ZipOutputStream;
* <p>
* 代码生成器
*/
@Slf4j
@Service
@AllArgsConstructor
@RequiredArgsConstructor
public class GeneratorServiceImpl implements GeneratorService {
private final GenFormConfMapper genFormConfMapper;
private final GenTableColumnService columnService;
private final GenCodeService element;
private final GenFormConfService formConfService;
private final Map<String, GenCodeService> genCodeServiceMap;
private final GenFieldTypeService fieldTypeService;
private final GenTableService tableService;
private final GenGroupService genGroupService;
private final GenTemplateService genTemplateService;
/**
* 分页查询表
* @param tableName 查询条件
* @param dsName
* @return
* 生成代码zip写出
* @param tableId 表
* @param zip 输出流
*/
@Override
public IPage<Map<String, Object>> getPage(Page page, String tableName, String dsName) {
GeneratorMapper mapper = element.getMapper(dsName);
// 手动切换数据源
DynamicDataSourceContextHolder.push(dsName);
@SneakyThrows
public void downloadCode(Long tableId, ZipOutputStream zip) {
// 数据模型
Map<String, Object> dataModel = getDataModel(tableId);
// 关闭SQL 优化
page.setOptimizeCountSql(false);
return mapper.queryTable(page, tableName);
}
Long style = (Long) dataModel.get("style");
@Override
public Map<String, Map> previewCode(GenConfig genConfig) {
// 根据tableName 查询最新的表单配置
List<GenFormConf> formConfList = genFormConfMapper.selectList(Wrappers.<GenFormConf>lambdaQuery()
.eq(GenFormConf::getTableName, genConfig.getTableName()).orderByDesc(GenFormConf::getCreateTime));
GroupVo groupVo = genGroupService.getGroupVoById(style);
List<GenTemplateEntity> templateList = groupVo.getTemplateList();
String tableNames = genConfig.getTableName();
String dsName = genConfig.getDsName();
for (GenTemplateEntity template : templateList) {
String templateCode = template.getTemplateCode();
String generatorPath = template.getGeneratorPath();
GenCodeService genCodeService = genCodeServiceMap.get(StyleTypeEnum.getDecs(genConfig.getStyle()));
GeneratorMapper mapper = genCodeService.getMapper(genConfig.getDsName());
String content = VelocityKit.renderStr(templateCode, dataModel);
String path = VelocityKit.renderStr(generatorPath, dataModel);
for (String tableName : StrUtil.split(tableNames, StrUtil.DASHED)) {
// 查询表信息
Map<String, String> table = mapper.queryTable(tableName, dsName);
// 查询列信息
List<Map<String, String>> columns = mapper.selectMapTableColumn(tableName, dsName);
// 生成代码
if (CollUtil.isNotEmpty(formConfList)) {
return genCodeService.gen(genConfig, table, columns, null, formConfList.get(0));
}
else {
return genCodeService.gen(genConfig, table, columns, null, null);
}
// 添加到zip
zip.putNextEntry(new ZipEntry(path));
IoUtil.writeUtf8(zip, false, content);
zip.flush();
zip.closeEntry();
}
return MapUtil.empty();
}
/**
* 生成代码
* @param genConfig 生成配置
* @return
* 表达式优化的预览代码方法
* @param tableId 表
* @return [{模板名称:渲染结果}]
*/
@Override
public byte[] generatorCode(GenConfig genConfig) {
// 根据tableName 查询最新的表单配置
List<GenFormConf> formConfList = genFormConfMapper.selectList(Wrappers.<GenFormConf>lambdaQuery()
.eq(GenFormConf::getTableName, genConfig.getTableName()).orderByDesc(GenFormConf::getCreateTime));
@SneakyThrows
public List<Map<String, String>> preview(Long tableId) {
// 数据模型
Map<String, Object> dataModel = getDataModel(tableId);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
Long style = (Long) dataModel.get("style");
String tableNames = genConfig.getTableName();
String dsName = genConfig.getDsName();
// 获取模板列表,Lambda 表达式简化代码
List<GenTemplateEntity> templateList = genGroupService.getGroupVoById(style).getTemplateList();
GenCodeService genCodeService = genCodeServiceMap.get(StyleTypeEnum.getDecs(genConfig.getStyle()));
GeneratorMapper mapper = genCodeService.getMapper(dsName);
return templateList.stream().map(template -> {
String templateCode = template.getTemplateCode();
String generatorPath = template.getGeneratorPath();
for (String tableName : StrUtil.split(tableNames, StrUtil.DASHED)) {
// 查询表信息
Map<String, String> table = mapper.queryTable(tableName, dsName);
// 查询列信息
List<Map<String, String>> columns = mapper.selectMapTableColumn(tableName, dsName);
// 生成代码
if (CollUtil.isNotEmpty(formConfList)) {
genCodeService.gen(genConfig, table, columns, zip, formConfList.get(0));
}
else {
genCodeService.gen(genConfig, table, columns, zip, null);
}
String content = VelocityKit.renderStr(templateCode, dataModel);
String path = VelocityKit.renderStr(generatorPath, dataModel);
// 使用 map 简化代码
return new HashMap<String, String>(4) {
{
put("code", content);
put("codePath", path);
}
};
}).collect(Collectors.toList());
}
/**
* 目标目录写入渲染结果方法
* @param tableId 表
*/
@Override
public void generatorCode(Long tableId) {
// 数据模型
Map<String, Object> dataModel = getDataModel(tableId);
Long style = (Long) dataModel.get("style");
// 获取模板列表,Lambda 表达式简化代码
List<GenTemplateEntity> templateList = genGroupService.getGroupVoById(style).getTemplateList();
templateList.forEach(template -> {
String templateCode = template.getTemplateCode();
String generatorPath = template.getGeneratorPath();
String content = VelocityKit.renderStr(templateCode, dataModel);
String path = VelocityKit.renderStr(generatorPath, dataModel);
FileUtil.writeUtf8String(content, path);
});
}
/**
* 获取表单设计器需要的 JSON 方法
* @param dsName 数据源名称
* @param tableName 表名称
* @return JSON 字符串
*/
@SneakyThrows
@Override
public String vform(String dsName, String tableName) {
// 查询表的元数据
GenTable genTable = tableService.queryOrBuildTable(dsName, tableName);
// 获取数据模型
Map<String, Object> dataModel = getDataModel(genTable.getId());
// 获取模板信息,Lambda 表达式简化代码
GenTemplateEntity genTemplateEntity = Optional
.ofNullable(genTemplateService.getById(GeneratorStyleEnum.VFORM_JSON.getTemplateId()))
.orElseThrow(() -> new Exception("模板不存在"));
// 渲染模板并返回结果
return VelocityKit.renderStr(genTemplateEntity.getTemplateCode(), dataModel);
}
/**
* 获取表单设计器需要的 JSON 方法
* @param id 表单配置 ID
* @return JSON 字符串
*/
@SneakyThrows
@Override
public String vformSfc(Long id) {
// 获取表单配置信息
GenFormConf formConf = formConfService.getById(id);
// 查询表的元数据
GenTable genTable = tableService.queryOrBuildTable(formConf.getDsName(), formConf.getTableName());
// 获取数据模型
Map<String, Object> dataModel = getDataModel(genTable.getId());
// 解析组件列表
List<JSONObject> widgetList = formConfService.parse(formConf.getFormInfo());
dataModel.put("widgetList", widgetList);
// 获取模板信息
GenTemplateEntity genTemplateEntity = Optional
.ofNullable(genTemplateService.getById(GeneratorStyleEnum.VFORM_FORM.getTemplateId()))
.orElseThrow(() -> new Exception("模板不存在"));
// 渲染模板并返回结果
return VelocityKit.renderStr(genTemplateEntity.getTemplateCode(), dataModel);
}
/**
* 通过 Lambda 表达式优化的获取数据模型方法
* @param tableId 表格 ID
* @return 数据模型 Map 对象
*/
private Map<String, Object> getDataModel(Long tableId) {
// 获取表格信息
GenTable table = tableService.getById(tableId);
// 获取字段列表
List<GenTableColumnEntity> fieldList = columnService.lambdaQuery()
.eq(GenTableColumnEntity::getDsName, table.getDsName())
.eq(GenTableColumnEntity::getTableName, table.getTableName()).list();
table.setFieldList(fieldList);
// 创建数据模型对象
Map<String, Object> dataModel = new HashMap<>();
// 填充数据模型
dataModel.put("dbType", table.getDbType());
dataModel.put("package", table.getPackageName());
dataModel.put("packagePath", table.getPackageName().replace(".", File.separator));
dataModel.put("version", table.getVersion());
dataModel.put("moduleName", table.getModuleName());
dataModel.put("ModuleName", StrUtil.upperFirst(table.getModuleName()));
dataModel.put("functionName", table.getFunctionName());
dataModel.put("FunctionName", StrUtil.upperFirst(table.getFunctionName()));
dataModel.put("formLayout", table.getFormLayout());
dataModel.put("style", table.getStyle());
dataModel.put("author", table.getAuthor());
dataModel.put("datetime", DateUtil.now());
dataModel.put("date", DateUtil.today());
setFieldTypeList(dataModel, table);
// 获取导入的包列表
Set<String> importList = fieldTypeService.getPackageByTableId(table.getDsName(), table.getTableName());
dataModel.put("importList", importList);
dataModel.put("tableName", table.getTableName());
dataModel.put("tableComment", table.getTableComment());
dataModel.put("className", StrUtil.lowerFirst(table.getClassName()));
dataModel.put("ClassName", table.getClassName());
dataModel.put("fieldList", table.getFieldList());
dataModel.put("backendPath", table.getBackendPath());
dataModel.put("frontendPath", table.getFrontendPath());
return dataModel;
}
/**
* 将表字段按照类型分组并存储到数据模型中
* @param dataModel 存储数据的 Map 对象
* @param table 表信息对象
*/
private void setFieldTypeList(Map<String, Object> dataModel, GenTable table) {
// 按字段类型分组,使用 Map 存储不同类型的字段列表
Map<Boolean, List<GenTableColumnEntity>> typeMap = table.getFieldList().stream()
.collect(Collectors.partitioningBy(GenTableColumnEntity::isPrimaryPk));
// 从分组后的 Map 中获取不同类型的字段列表
List<GenTableColumnEntity> primaryList = typeMap.get(true);
List<GenTableColumnEntity> formList = typeMap.get(false).stream().filter(GenTableColumnEntity::isFormItem)
.collect(Collectors.toList());
List<GenTableColumnEntity> gridList = typeMap.get(false).stream().filter(GenTableColumnEntity::isGridItem)
.collect(Collectors.toList());
List<GenTableColumnEntity> queryList = typeMap.get(false).stream().filter(GenTableColumnEntity::isQueryItem)
.collect(Collectors.toList());
if (CollUtil.isNotEmpty(primaryList)) {
dataModel.put("pk", primaryList.get(0));
}
IoUtil.close(zip);
return outputStream.toByteArray();
dataModel.put("primaryList", primaryList);
dataModel.put("formList", formList);
dataModel.put("gridList", gridList);
dataModel.put("queryList", queryList);
}
}
@@ -1,112 +0,0 @@
package com.pig4cloud.pigx.codegen.service.impl.temp;
import cn.hutool.core.io.IoUtil;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import com.pig4cloud.pigx.codegen.entity.TableEntity;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* avue代码实现
*
* @author lengleng
* @date 2022/7/11
*/
@Service("avue")
public class AvueGenCodeServiceImpl implements GenCodeService {
private final String CRUD_PREFIX = "export const tableOption =";
/**
* 注入支持的模板列表
* @param config 用户输入
* @return ListString
*/
@Override
public List<String> getTemplates(GenConfig config) {
List<String> templates = GenCodeService.super.getTemplates(config);
templates.add("template/avue/index.vue.vm");
templates.add("template/avue/crud.js.vm");
templates.add("template/avue/api.js.vm");
return templates;
}
/**
* 获取文件名
* @param template
* @param className
* @param packageName
* @param moduleName
*/
@Override
public String getFileName(String template, String className, String packageName, String moduleName) {
if (template.contains("avue/index.vue.vm")) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views"
+ File.separator + moduleName + File.separator + className.toLowerCase() + File.separator
+ "index.vue";
}
if (template.contains("avue/api.js.vm")) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "api" + File.separator
+ className.toLowerCase() + ".js";
}
if (template.contains("avue/crud.js.vm")) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "const"
+ File.separator + "crud" + File.separator + className.toLowerCase() + ".js";
}
return GenCodeService.super.getFileName(template, className, packageName, moduleName);
}
/**
* 渲染数据
* @param genConfig 用户输入相关
* @param zip 输出zip流
* @param tableEntity 表格实体
* @param map 参数集合
* @param formConf 表单设计
* @return
*/
@SneakyThrows
public Map<String, Map> renderData(GenConfig genConfig, ZipOutputStream zip, TableEntity tableEntity,
Map<String, Object> map, GenFormConf formConf) {
Map<String, Map> resultMap = new HashMap<>();
if (Objects.nonNull(formConf)) {
Map<String, String> templatesData = new HashMap<>();
// 存在 curd 存在设计好的JSON 则使用Json 覆盖
String crudTempName = "template/avue/crud.js.vm";
String fileName = getFileName(crudTempName, tableEntity.getCaseClassName(), map.get("package").toString(),
map.get("moduleName").toString());
String contents = CRUD_PREFIX + formConf.getFormInfo();
templatesData.put("codePath", fileName);
templatesData.put("code", contents);
if (zip != null) {
zip.putNextEntry(new ZipEntry(Objects.requireNonNull(fileName)));
IoUtil.write(zip, StandardCharsets.UTF_8, false, contents);
}
resultMap.putAll(GenCodeService.super.renderData(genConfig, zip, tableEntity, map, formConf));
resultMap.put(crudTempName, templatesData);
return resultMap;
}
return GenCodeService.super.renderData(genConfig, zip, tableEntity, map, formConf);
}
}
@@ -1,62 +0,0 @@
package com.pig4cloud.pigx.codegen.service.impl.temp;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.List;
/**
* element代码实现
*
* @author lengleng
* @date 2022/7/11
*/
@Service("element")
public class EleGenCodeServiceImpl implements GenCodeService {
/**
* 注入支持的模板列表
* @param config 用户输入
* @return ListString
*/
@Override
public List<String> getTemplates(GenConfig config) {
List<String> templates = GenCodeService.super.getTemplates(config);
templates.add("template/element/index.vue.vm");
templates.add("template/element/form.vue.vm");
templates.add("template/element/api.js.vm");
return templates;
}
/**
* 获取文件名
* @param template
* @param className
* @param packageName
* @param moduleName
*/
@Override
public String getFileName(String template, String className, String packageName, String moduleName) {
if (template.contains("element/index.vue.vm")) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views"
+ File.separator + moduleName + File.separator + className.toLowerCase() + File.separator
+ "index.vue";
}
if (template.contains("element/form.vue.vm")) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views"
+ File.separator + moduleName + File.separator + className.toLowerCase() + File.separator
+ className.toLowerCase() + "-form.vue";
}
if (template.contains("element/api.js.vm")) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "api" + File.separator
+ className.toLowerCase() + ".js";
}
return GenCodeService.super.getFileName(template, className, packageName, moduleName);
}
}
@@ -1,37 +0,0 @@
package com.pig4cloud.pigx.codegen.service.impl.temp;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* magic代码实现
*
* @author lengleng
* @date 2022/7/11
*/
@Service("magic")
public class MagicGenCodeServiceImpl implements GenCodeService {
/**
* 注入支持的模板列表
* @param config 用户输入
* @return ListString
*/
@Override
public List<String> getTemplates(GenConfig config) {
List<String> templates = GenCodeService.super.getTemplates(config);
templates.add("template/avue/index.vue.vm");
templates.add("template/avue/crud.js.vm");
templates.add("template/avue/api.js.vm");
templates.add("template/magic/query.magic.vm");
templates.add("template/magic/del.magic.vm");
templates.add("template/magic/add.magic.vm");
templates.add("template/magic/update.magic.vm");
templates.add("template/magic/metadata.magic.vm");
return templates;
}
}
@@ -1,67 +0,0 @@
package com.pig4cloud.pigx.codegen.service.impl.temp;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.List;
/**
* uview代码实现
*
* @author lengleng
* @date 2022/7/11
*/
@Service("uview")
public class UviewGenCodeServiceImpl implements GenCodeService {
/**
* 注入支持的模板列表
* @param config 用户输入
* @return ListString
*/
@Override
public List<String> getTemplates(GenConfig config) {
List<String> templates = GenCodeService.super.getTemplates(config);
templates.add("template/uview/index.vue.vm");
templates.add("template/uview/form.vue.vm");
templates.add("template/uview/api.js.vm");
templates.add("template/uview/page.json.vm");
return templates;
}
/**
* 获取文件名
* @param template
* @param className
* @param packageName
* @param moduleName
*/
@Override
public String getFileName(String template, String className, String packageName, String moduleName) {
if (template.contains("uview/index.vue.vm")) {
return CommonConstants.UNI_END_PROJECT + File.separator + "pages" + File.separator + moduleName
+ File.separator + className.toLowerCase() + File.separator + className.toLowerCase()
+ "-index.vue";
}
if (template.contains("uview/form.vue.vm")) {
return CommonConstants.UNI_END_PROJECT + File.separator + "pages" + File.separator + moduleName
+ File.separator + className.toLowerCase() + File.separator + className.toLowerCase() + "-form.vue";
}
if (template.contains("uview/api.js.vm")) {
return CommonConstants.UNI_END_PROJECT + File.separator + "common" + File.separator
+ className.toLowerCase() + ".api.js";
}
if (template.contains("uview/page.json.vm")) {
return className.toLowerCase() + ".page.json";
}
return GenCodeService.super.getFileName(template, className, packageName, moduleName);
}
}
@@ -0,0 +1,12 @@
package com.pig4cloud.pigx.codegen.util;
/**
* 字段自动填充 枚举
*
* @author 阿沐 babamu@126.com
*/
public enum AutoFillEnum {
DEFAULT, INSERT, UPDATE, INSERT_UPDATE, CREATE;
}
@@ -0,0 +1,62 @@
package com.pig4cloud.pigx.codegen.util;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author lengleng
* @date 2023/3/12
* <p>
* 通用字段的填充策略和显示策略
*/
@Getter
@AllArgsConstructor
public enum CommonColumnFiledEnum {
/**
* create_by 字段
*/
create_by(false, false, AutoFillEnum.INSERT.name(), 100),
/**
* create_time 字段
*/
create_time(false, false, AutoFillEnum.INSERT.name(), 101),
/**
* update_by 字段
*/
update_by(false, false, AutoFillEnum.INSERT_UPDATE.name(), 102),
/**
* update_time 字段
*/
update_time(false, false, AutoFillEnum.INSERT_UPDATE.name(), 103),
/**
* del_flag 字段
*/
del_flag(false, false, AutoFillEnum.DEFAULT.name(), 104),
/**
* tenant_id 字段
*/
tenant_id(false, false, AutoFillEnum.DEFAULT.name(), 105);
/**
* 表单是否默认显示
*/
private Boolean formItem;
/**
* 表格是否默认显示
*/
private Boolean gridItem;
/**
* 自动填充策略
*/
private String autoFill;
/**
* 排序值
*/
private Integer sort;
}
@@ -0,0 +1,32 @@
package com.pig4cloud.pigx.codegen.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import java.util.HashSet;
import java.util.List;
/**
* @author lengleng
* @date 2023/2/7
*/
public class DictTool {
/**
* 将字段列表转换为带有双引号的逗号分隔的字符串
* @return 带有双引号的逗号分隔的字符串
*/
public static String quotation(List<String> fields) {
return CollUtil.join(new HashSet<>(fields), StrUtil.COMMA, s -> String.format("'%s'", s));
}
/**
* 将字段列表转换为逗号分隔的字符串
* @return 逗号分隔的字符串
*/
public static String format(List<String> fields) {
return CollUtil.join(new HashSet<>(fields), StrUtil.COMMA);
}
}
@@ -0,0 +1,19 @@
package com.pig4cloud.pigx.codegen.util;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 表单布局 枚举
*
* @author 阿沐 babamu@126.com
*/
@Getter
@AllArgsConstructor
public enum FormLayoutEnum {
ONE(1), TWO(2);
private final Integer value;
}
@@ -0,0 +1,81 @@
package com.pig4cloud.pigx.codegen.util;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pig4cloud.pigx.codegen.entity.GenDatasourceConf;
import com.pig4cloud.pigx.codegen.mapper.GenDatasourceConfMapper;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.common.core.util.SpringContextHolder;
import com.pig4cloud.pigx.common.datasource.util.DsJdbcUrlEnum;
import lombok.experimental.UtilityClass;
import org.springframework.context.ApplicationContext;
import java.util.Map;
/**
* 代码生成工具类
*
* @author lengleng
* @date 2023/2/16
*/
@UtilityClass
public class GenKit {
/**
* 获取功能名
* @param tableName 表名
* @return 功能名
*/
public String getFunctionName(String tableName) {
String functionName = StrUtil.subAfter(tableName, "_", true);
if (StrUtil.isBlank(functionName)) {
functionName = tableName;
}
return functionName;
}
/**
* 获取模块名称
* @param packageName 包名
* @return 功能名
*/
public String getModuleName(String packageName) {
return StrUtil.subAfter(packageName, ".", true);
}
/**
* 获取数据源对应方言的mapper
* @param dsName 数据源名称
* @return GeneratorMapper
*/
public GeneratorMapper getMapper(String dsName) {
// 获取目标数据源数据库类型
GenDatasourceConfMapper datasourceConfMapper = SpringContextHolder.getBean(GenDatasourceConfMapper.class);
GenDatasourceConf datasourceConf = datasourceConfMapper
.selectOne(Wrappers.<GenDatasourceConf>lambdaQuery().eq(GenDatasourceConf::getName, dsName));
String dbConfType;
// 默认MYSQL 数据源
if (datasourceConf == null) {
dbConfType = DsJdbcUrlEnum.MYSQL.getDbName();
}
else {
dbConfType = datasourceConf.getDsType();
}
// 获取全部数据实现
ApplicationContext context = SpringContextHolder.getApplicationContext();
Map<String, GeneratorMapper> beansOfType = context.getBeansOfType(GeneratorMapper.class);
// 根据数据类型选择mapper
for (String key : beansOfType.keySet()) {
if (StrUtil.containsIgnoreCase(key, dbConfType)) {
return beansOfType.get(key);
}
}
throw new IllegalArgumentException("dsName 不合法: " + dsName);
}
}
@@ -0,0 +1,29 @@
package com.pig4cloud.pigx.codegen.util;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 代码生成主题
*
* @author 冷冷
*/
@Getter
@AllArgsConstructor
public enum GeneratorStyleEnum {
VFORM_JSON(1L, "element-plus 风格"),
VFORM_FORM(2L, "uview 风格");
/**
* 对应模板ID
*/
private Long templateId;
/**
* 描述
*/
private String desc;
}
@@ -0,0 +1,19 @@
package com.pig4cloud.pigx.codegen.util;
/**
* 代码生成方式 枚举
*
* @author 阿沐 babamu@126.com
*/
public enum GeneratorTypeEnum {
/**
* zip压缩包
*/
ZIP_DOWNLOAD,
/**
* 自定义目录
*/
CUSTOM_DIRECTORY;
}
@@ -0,0 +1,31 @@
package com.pig4cloud.pigx.codegen.util;
import cn.hutool.core.text.NamingCase;
/**
* 命名规则处理,针对驼峰,下划线等处理
*
* @author lengleng
* @date 2023/1/31
*/
public class NamingCaseTool {
/**
* 传入字段获取的get方法
* @param in 字段名称
* @return
*/
public static String getProperty(String in) {
return String.format("get%s", NamingCase.toPascalCase(in));
}
/**
* 首字母大写
* @param in 字段
* @return 首字母大写
*/
public static String pascalCase(String in) {
return String.format(NamingCase.toPascalCase(in));
}
}
@@ -0,0 +1,69 @@
package com.pig4cloud.pigx.codegen.util;
import cn.hutool.core.util.CharsetUtil;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.generic.DateTool;
import org.apache.velocity.tools.generic.MathTool;
import org.springframework.stereotype.Service;
import java.io.StringWriter;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
/**
* 模板引擎工具类
*
* @author lengleng
* @date 2023/2/7
*/
@Service
public class VelocityKit {
/**
* Velocity 模板渲染方法
* @param template 模板
* @param map 数据模型
* @return 渲染结果
*/
public static String render(String template, Map<String, Object> map) {
// 设置velocity资源加载器
Properties prop = new Properties();
prop.put("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(prop);
VelocityContext context = new VelocityContext(map);
// 函数库,使用 Lambda 表达式简化代码
Optional.of(new MathTool()).ifPresent(mt -> context.put("math", mt));
Optional.of(new DateTool()).ifPresent(dt -> context.put("dateTool", dt));
Optional.of(new DictTool()).ifPresent(dt -> context.put("dict", dt));
Optional.of(new NamingCaseTool()).ifPresent(nct -> context.put("str", nct));
// 渲染模板,使用 Lambda 表达式简化代码
StringWriter sw = new StringWriter();
Optional.ofNullable(Velocity.getTemplate(template, CharsetUtil.UTF_8)).ifPresent(tpl -> tpl.merge(context, sw));
return sw.toString();
}
/**
* 渲染文本
* @param str
* @param dataModel 数据
* @return
*/
public static String renderStr(String str, Map<String, Object> dataModel) {
// 设置velocity资源加载器
Velocity.init();
StringWriter stringWriter = new StringWriter();
VelocityContext context = new VelocityContext(dataModel);
// 函数库
context.put("math", new MathTool());
context.put("dateTool", new DateTool());
context.put("dict", new DictTool());
context.put("str", new NamingCaseTool());
Velocity.evaluate(context, stringWriter, "renderStr", str);
return stringWriter.toString();
}
}
@@ -0,0 +1,45 @@
package com.pig4cloud.pigx.codegen.util.vo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.pig4cloud.pigx.codegen.entity.GenTemplateEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
@Data
public class GroupVo {
/**
* id
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "id")
private Long id;
/**
* 分组名称
*/
@Schema(description = "分组名称")
private String groupName;
/**
* 分组描述
*/
@Schema(description = "分组描述")
private String groupDesc;
/**
* 模板ids
*/
@Schema(description = "拥有的模板列表")
private Long[] templateId;
/**
* 模板列表
*/
@Schema(description = "拥有的模板列表")
private List<GenTemplateEntity> templateList;
}
@@ -1,4 +1,4 @@
package com.pig4cloud.pigx.codegen.util;
package com.pig4cloud.pigx.codegen.util.vo;
import lombok.Data;
@@ -0,0 +1,21 @@
package com.pig4cloud.pigx.codegen.util.vo;
import com.pig4cloud.pigx.codegen.entity.GenGroupEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
@Data
@Schema(description = "模板传输对象")
@EqualsAndHashCode(callSuper = true)
public class TemplateGroupDTO extends GenGroupEntity {
/**
* 模板id集合
*/
@Schema(description = "模板id集合")
private List<Long> templateId;
}
@@ -0,0 +1,25 @@
# 数据源
spring:
redis:
host: pigx-redis
database: 9 #避免和微服务 PIGX 冲突
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://pigx-mysql:3306/pigxx_boot_codegen?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&allowPublicKeyRetrieval=true
web:
resources:
static-locations: classpath:/static/,classpath:/views/
# 租户表维护
pigx:
tenant:
column: tenant_id
tables:
- gen_datasource_conf
- gen_form_conf
- gen_template
- gen_group
@@ -1,70 +0,0 @@
#\u4EE3\u7801\u751F\u6210\u5668\uFF0C\u914D\u7F6E\u4FE1\u606F
mainPath=com.pig4cloud.pigx
#\u5305\u540D
package=com.pig4cloud.pigx
moduleName=generator
#\u4F5C\u8005
author=pigx code generator
#\u8868\u524D\u7F00(\u7C7B\u540D\u4E0D\u4F1A\u5305\u542B\u8868\u524D\u7F00)
tablePrefix=tb_
# hidden columns in Swagger Models
hiddenColumn=tenant_id
#MYSQL \u7C7B\u578B\u8F6C\u6362
tinyint=Integer
smallint=Integer
mediumint=Integer
int=Integer
integer=Integer
bigint=Long
float=Float
double=Double
decimal=BigDecimal
bit=Boolean
char=String
varchar=String
tinytext=String
text=String
mediumtext=String
longtext=String
date=LocalDateTime
datetime=LocalDateTime
timestamp=LocalDateTime
# PG \u7C7B\u578B\u8F6C\u5316\u89C4\u5219
int2=Integer
int4=Integer
int8=Long
bpchar=String
float4=Float
float8=Float
#ORACLE \u7279\u6B8A\u7C7B\u578B\u8F6C\u6362\u89C4\u5219
INT=Integer
INTEGER=Integer
LONG=LONG
NUMBER=Integer
BINARY_INTEGER=Integer
FLOAT=Float
BINARY_FLOAT=Float
DOUBLE=Double
BINARY_DOUBLE=Double
DECIMAL=BigDecimal
CHAR=String
VARCHAR=String
VARCHAR2=String
NVARCHAR=String
NVARCHAR2=String
DATE=LocalDateTime
DATETIME=LocalDateTime
TIMESTAMP=LocalDateTime
CLOB=String
BLOB=String
# MSSQL \u7C7B\u578B
nvarchar=String
nchar=String
datetime2=LocalDateTime
#\u8FBE\u68A6
BIGINT=Long
@@ -80,7 +80,7 @@
<appender-ref ref="error"/>
</logger>
<!-- Level: FATAL 0 ERROR 3 WARN 4 INFO 6 DEBUG 7 -->
<root level="INFO">
<root level="debug">
<appender-ref ref="console"/>
<appender-ref ref="debug"/>
<appender-ref ref="error"/>
@@ -1,212 +0,0 @@
var MAGIC_EDITOR_CONFIG = {
title: '接口低代码设计平台',
theme: 'dark',
defaultExpand: true,
checkUpdate: false,
jdbcDrivers: ['com.mysql.cj.jdbc.Driver', 'com.mysql.jdbc.Driver', 'oracle.jdbc.driver.OracleDriver', 'org.postgresql.Driver', 'com.microsoft.sqlserver.jdbc.SQLServerDriver'],
blockClose: true, // 是否阻止离开页面
autoSave: true,
decorationTimeout: 10000,
logMaxRows: Infinity,
editorFontFamily: 'JetBrainsMono, Consolas, "Courier New",monospace, 微软雅黑',
editorFontSize: 14,
fontLigatures: true,
header: {
skin: true, document: true, repo: true, qqGroup: true
},
request: {
beforeSend: function (config) {
let tenant_id = new URL(window.location.href).searchParams.get("tenant_id");
config.headers["TENANT-ID"] = tenant_id === null ? 1 : tenant_id
let access_token = new URL(window.location.href).searchParams.get("access_token");
if (access_token !== null) {
config.headers["Authorization"] = `Bearer ${access_token}`
}
return config;
}, onError: function (err) {
return Promise.reject(err)
}
},
response: {
onSuccess: function (resp) {
if (resp.data.code === -1) {
window.location.href = '/'
}
return resp;
}, onError: function (err) {
console.log('请求失败', err)
return Promise.reject(err)
},
},
themes: {
editor: {
base: 'vs-dark',
rules: [{foreground: 'A9B7C6'}, {
token: 'keywords',
foreground: 'CC7832',
fontStyle: 'bold'
}, {token: 'keyword', foreground: 'CC7832', fontStyle: 'bold'}, {
token: 'number',
foreground: '6897BB'
}, {token: 'string', foreground: '6A8759', fontStyle: 'bold'}, {
token: 'string.sql',
foreground: '6A8759'
}, {token: 'tag.sql', foreground: 'E8BF6A'}, {
token: 'attribute.name.sql',
foreground: 'BABABA'
}, {token: 'attribute.value.sql', foreground: '6A8759'}, {
token: 'predefined.sql',
foreground: 'A9B7C6',
fontStyle: 'italic'
}, {token: 'predefined.magicscript', foreground: 'A9B7C6', fontStyle: 'italic'}, {
token: 'key',
foreground: '9876AA'
}, {token: 'string.key.json', foreground: '9876AA'}, {
token: 'string.value.json',
foreground: '6A8759'
}, {token: 'keyword.json', foreground: '6897BB'}, {
token: 'operator.sql',
foreground: 'CC7832',
fontStyle: 'bold'
}, {token: 'string.invalid', foreground: '008000', background: 'FFCCCC'}, {
token: 'string.escape.invalid',
foreground: '008000',
background: 'FFCCCC'
}, {token: 'string.escape', foreground: '000080', fontStyle: 'bold'}, {
token: 'comment',
foreground: '808080',
fontStyle: 'italic'
}, {token: 'comment.doc', foreground: '629755', fontStyle: 'italic'}, {
token: 'comment.todo',
foreground: 'A8C023',
fontStyle: 'italic'
}, {token: 'string.escape', foreground: 'CC7832'}],
colors: {
'editor.background': '#2B2B2B', 'editorLineNumber.foreground': '#999999', //行号的颜色
'editorGutter.background': '#313335', //行号背景色
'editor.lineHighlightBackground': '#323232', //光标所在行的颜色
'dropdown.background': '#3C3F41', //右键菜单
'dropdown.foreground': '#BBBBBB', //右键菜单文字颜色
'list.activeSelectionBackground': '#4B6EAF', //右键菜单悬浮背景色
'list.activeSelectionForeground': '#FFFFFF', //右键菜单悬浮文字颜色
'editorSuggestWidget.selectedBackground': '#113A5C' //代码提示选中行的背景色
}
}, styles: {
'main-background-color': '#3C3F41', // 主要背景色
'main-border-color': '#323232', // 主要边框色
'main-color': '#bbb', // 主要文字颜色
'main-selected-background-color': '#323232', // 主要选中背景色
'main-hover-background-color': '#353739', // 主要悬浮背景色
'main-hover-icon-background-color': '#4C5052', // 主要悬浮图标背景色
'main-selected-color': '#fff', // 主要选中文字颜色
'main-icon-color': '#AFB1B3', // 主要图标颜色
'header-title-color': '#bbb', // 顶部名字颜色
'header-version-color': '#999', // 顶部版本号颜色
'header-default-color': '#AFB1B3', // 顶部其它文字颜色
'empty-background-color': '#282828', // 中间空的背景颜色
'empty-key-color': '#489DF6', // 中间空的快捷键文字颜色
'empty-color': '#A0A0A0', // 中间空的文字颜色
'button-hover-background-color': '#365880', // 按钮悬浮背景颜色
'button-hover-border-color': '#43688C', // 按钮悬浮边框颜色
'button-background-color': '#4C5052', // 按钮背景颜色
'button-border-color': '#5E6060', // 按钮边框颜色
'button-disabled-color': '#5a5a5a', // 按钮禁用时的颜色
'navbar-body-background-color': '#3C3F41', // 导航条内容背景颜色
'navbar-body-border-color': '#555555', //导航条内边框颜色
'resource-label-color': '#bbb', // 资源树形菜单label颜色
'resource-span-color': '#787878', // 资源树形菜单span颜色
'tree-hover-background-color': '#0d293e', // 树形菜单悬浮背景色
'tree-icon-color': '#aeb9c0', // 树形菜单图标颜色
'table-border-color': '#646464', // 表格边框颜色
'input-border-color': '#646464', // input边框颜色
'input-foucs-color': '#3D6185', // input focus边框颜色
'input-background-color': '#45494A', // input背景颜色
'select-background-color': '#3C3F41', // select背景颜色
'select-hover-background-color': '#3C3F41', // select悬浮背景色
'select-option-background-color': '#3C3F41', // select选项背景色
'select-option-hover-background-color': '#4B6EAF', // select选项悬浮背景色
'select-option-border-color': '#808080', // select选项边框色
// 数据类型颜色
'data-type-default-color': '#a9b7c6',
'data-type-string-color': '#6a8759',
'data-type-integer-color': '#6897bb',
'data-type-byte-color': '#6897bb',
'data-type-long-color': '#6897bb',
'data-type-float-color': '#6897bb',
'data-type-double-color': '#6897bb',
'data-type-short-color': '#6897bb',
'data-type-number-color': '#6897bb',
'data-type-boolean-color': '#cc7832',
'data-type-class-color': '#9876aa',
'data-type-key-color': '#FF8E8E',
'run-log-background-color': '#2b2b2b', // 运行日志背景颜色
// 日志级别颜色
'log-level-info': '#ABC023',
'log-level-error': '#CC666E',
'log-level-debug': '#299999',
'log-level-warn': 'unset',
'log-level-trace': '#5394EC',
'log-color-cyan': '#009191',
'log-color-link': '#287BDE',
'todo-color': '#A8C023',
'debug-line-background-color': '#2D6099', // 调试时,断点行背景颜色
'breakpoints-background-color': '#C75450', // 断点圆圈背景颜色
'breakpoint-line-background-color': '#3a2323', // 断点所在行的背景颜色
'select-inputable-background-color': '#45494a', // select输入框背景颜色
'select-inputable-border': 'transparent',
'tab-selected-background-color': '#4E5254', // tab 选中时的背景颜色
'message-em-color': '#68dd9a', // 消息 em 颜色
'checkbox-background-color': '#43494A',
'checkbox-border-color': '#6B6B6B',
'checkbox-text-color': '#bbb',
'checkbox-selected-background-color': '#43494A',
'checkbox-selected-border-color': '#6B6B6B',
'toolbox-list-label-color': '#bbb',
'toolbox-list-span-color': '#787878',
'toolbox-border-color': '#323232',
'toolbox-list-hover-background': '#0D293E',
'toolbox-border-right-color': '#555555',
'footer-border-color': '#323232',
'tab-bar-border-color': '#323232',
'dialog-border-color': '#282828',
'dialog-shadow-color': '#151515',
'table-col-border-color': '#333638',
'table-row-border-color': '#333638',
'table-hover-background': '#4B6EAF',
'debug-line-background': '#2D6099',
'breakpoints-background': '#C75450',
'breakpoint-line-background': '#3a2323',
'table-even-background': '#414547',
'button-disabled-background': '#5A5A5A',
'toolbox-list-header-icon-color': '#AFB1B3',
'log-error-color': '#CC666E',
'text-string-color': '#6A8759',
'text-number-color': '#6897BB',
'text-boolean-color': '#CC7832',
'text-property-color': '#9876aa',
'text-key-color': '#9876aa',
'suggest-hover-background': '#113A5C',
'suggest-hover-color': '#fff',
'statusbar-em-color': '#68dd9a',
}
}
}
@@ -1,7 +0,0 @@
magic-api:
prod: true #生产模式鉴权
show-url: false
banner: false
web: /api/designer
editor-config: classpath:./magic/magic-editor-config.js
sql-column-case: camel
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pig4cloud.pigx.codegen.mapper.GenDynamicMapper">
<!-- 动态SQL查询 -->
<select id="dynamicQuerySql" parameterType="String" resultType="java.util.LinkedHashMap">
${value}
</select>
</mapper>
@@ -21,15 +21,21 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${package}.${moduleName}.mapper.${className}Mapper">
<mapper namespace="com.pig4cloud.pigx.codegen.mapper.GenFieldTypeMapper">
<resultMap id="${classname}Map" type="${package}.${moduleName}.entity.${className}">
#foreach($column in $columns)
#if($column.lowerAttrName==$pk.lowerAttrName)
<id property="${pk.lowerAttrName}" column="${pk.columnName}"/>
#else
<result property="${column.lowerAttrName}" column="${column.columnName}"/>
#end
#end
</resultMap>
<resultMap id="fieldTypeMap" type="com.pig4cloud.pigx.codegen.entity.GenFieldType">
<id property="id" column="id"/>
<result property="columnType" column="column_type"/>
<result property="attrType" column="attr_type"/>
<result property="packageName" column="package_name"/>
<result property="createTime" column="create_time"/>
</resultMap>
<select id="getPackageByTableId" resultType="String">
select t1.package_name
from gen_field_type t1,
gen_table_column t2
where t1.attr_type = t2.attr_type
and t2.ds_name = #{dsName} and t2.table_name = #{tableName}
</select>
</mapper>
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pig4cloud.pigx.codegen.mapper.GenGroupMapper">
<resultMap id="genGroupMap" type="com.pig4cloud.pigx.codegen.util.vo.GroupVo">
<id property="id" column="group_id"/>
<result property="groupName" column="group_name"/>
<result property="groupDesc" column="group_desc"/>
<collection property="templateList" ofType="com.pig4cloud.pigx.codegen.entity.GenTemplateEntity"
select="com.pig4cloud.pigx.codegen.mapper.GenTemplateMapper.listTemplateById" column="group_id">
</collection>
</resultMap>
<select id="getGroupVoById" resultMap="genGroupMap">
SELECT
g.id as group_id ,
g.group_name ,
g.group_desc
FROM
gen_group g
WHERE g.id = #{id}
</select>
</mapper>
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~
~ Copyright (c) 2018-2025, lengleng All rights reserved.
~
~ Redistribution and use in source and binary forms, with or without
~ modification, are permitted provided that the following conditions are met:
~
~ Redistributions of source code must retain the above copyright notice,
~ this list of conditions and the following disclaimer.
~ Redistributions in binary form must reproduce the above copyright
~ notice, this list of conditions and the following disclaimer in the
~ documentation and/or other materials provided with the distribution.
~ Neither the name of the pig4cloud.com developer nor the names of its
~ contributors may be used to endorse or promote products derived from
~ this software without specific prior written permission.
~ Author: lengleng (wangiegie@gmail.com)
~
-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pig4cloud.pigx.codegen.mapper.GenTableMapper">
<resultMap id="tableMap" type="com.pig4cloud.pigx.codegen.entity.GenTable">
<id property="id" column="id"/>
<result property="tableName" column="table_name"/>
<result property="className" column="class_name"/>
<result property="tableComment" column="table_comment"/>
<result property="author" column="author"/>
<result property="email" column="email"/>
<result property="packageName" column="package_name"/>
<result property="version" column="version"/>
<result property="generatorType" column="generator_type"/>
<result property="backendPath" column="backend_path"/>
<result property="frontendPath" column="frontend_path"/>
<result property="moduleName" column="module_name"/>
<result property="functionName" column="function_name"/>
<result property="formLayout" column="form_layout"/>
<result property="datasourceId" column="datasource_id"/>
<result property="baseclassId" column="baseclass_id"/>
<result property="createTime" column="create_time"/>
</resultMap>
</mapper>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pig4cloud.pigx.codegen.mapper.GenTemplateGroupMapper">
<resultMap id="genTemplateGroupMap" type="com.pig4cloud.pigx.codegen.entity.GenTemplateGroupEntity">
<id property="groupId" column="group_id"/>
<id property="templateId" column="template_id"/>
</resultMap>
</mapper>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pig4cloud.pigx.codegen.mapper.GenTemplateMapper">
<resultMap id="genTemplateMap" type="com.pig4cloud.pigx.codegen.entity.GenTemplateEntity">
<id property="id" column="id"/>
<result property="templateName" column="template_name"/>
<result property="generatorPath" column="generator_path"/>
<result property="templateDesc" column="template_desc"/>
<result property="templateCode" column="template_code"/>
</resultMap>
<select id="listTemplateById" resultType="com.pig4cloud.pigx.codegen.entity.GenTemplateEntity">
SELECT
t.id as id,t.template_name,t.generator_path,t.template_desc,t.template_code
FROM gen_template t ,
gen_template_group tg
WHERE t.id = tg.template_id
AND t.del_flag = '0'
and tg.group_id = #{groupId}
</select>
</mapper>
@@ -22,7 +22,6 @@
order by create_time desc
</select>
<sql id="queryColumn">
SELECT
column_name columnName,
@@ -1,129 +0,0 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package ${package}.${moduleName}.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import ${package}.${moduleName}.entity.${className};
import ${package}.${moduleName}.service.${className}Service;
import org.springframework.security.access.prepost.PreAuthorize;
import com.pig4cloud.pigx.common.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* ${comments}
*
* @author ${author}
* @date ${datetime}
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/${pathName}" )
@Tag(description = "${pathName}", name = "${comments}管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class ${className}Controller {
private final ${className}Service ${classname}Service;
/**
* 分页查询
* @param page 分页对象
* @param ${classname} ${comments}
* @return
*/
@Operation(summary = "分页查询", description = "分页查询")
@GetMapping("/page" )
@PreAuthorize("@pms.hasPermission('${moduleName}_${pathName}_view')" )
public R get${className}Page(Page page, ${className} ${classname}) {
return R.ok(${classname}Service.page(page, Wrappers.query(${classname})));
}
/**
* 通过id查询${comments}
* @param ${pk.lowerAttrName} id
* @return R
*/
@Operation(summary = "通过id查询", description = "通过id查询")
@GetMapping("/{${pk.lowerAttrName}}" )
@PreAuthorize("@pms.hasPermission('${moduleName}_${pathName}_view')" )
public R getById(@PathVariable("${pk.lowerAttrName}" ) ${pk.attrType} ${pk.lowerAttrName}) {
return R.ok(${classname}Service.getById(${pk.lowerAttrName}));
}
/**
* 新增${comments}
* @param ${classname} ${comments}
* @return R
*/
@Operation(summary = "新增${comments}", description = "新增${comments}")
@SysLog("新增${comments}" )
@PostMapping
@PreAuthorize("@pms.hasPermission('${moduleName}_${pathName}_add')" )
public R save(@RequestBody ${className} ${classname}) {
return R.ok(${classname}Service.save(${classname}));
}
/**
* 修改${comments}
* @param ${classname} ${comments}
* @return R
*/
@Operation(summary = "修改${comments}", description = "修改${comments}")
@SysLog("修改${comments}" )
@PutMapping
@PreAuthorize("@pms.hasPermission('${moduleName}_${pathName}_edit')" )
public R updateById(@RequestBody ${className} ${classname}) {
return R.ok(${classname}Service.updateById(${classname}));
}
/**
* 通过id删除${comments}
* @param ${pk.lowerAttrName} id
* @return R
*/
@Operation(summary = "通过id删除${comments}", description = "通过id删除${comments}")
@SysLog("通过id删除${comments}" )
@DeleteMapping("/{${pk.lowerAttrName}}" )
@PreAuthorize("@pms.hasPermission('${moduleName}_${pathName}_del')" )
public R removeById(@PathVariable ${pk.attrType} ${pk.lowerAttrName}) {
return R.ok(${classname}Service.removeById(${pk.lowerAttrName}));
}
/**
* 导出excel 表格
* @param ${classname} 查询条件
* @return excel 文件流
*/
@ResponseExcel
@GetMapping("/export")
@PreAuthorize("@pms.hasPermission('${moduleName}_${pathName}_export')" )
public List<${className}> export(${className} ${classname}) {
return ${classname}Service.list(Wrappers.query(${classname}));
}
}
@@ -1,19 +0,0 @@
export const tableOption = {
"border": true,
"index": true,
"indexLabel": "序号",
"stripe": true,
"menuAlign": "center",
"align": "center",
"searchMenuSpan": 6,
"column": [
#foreach ($column in $columns)
{
"type": "input",
"label": "$column.comments",
"prop": "$column.lowerAttrName",
"span": 12
}#if($foreach.hasNext),#end
#end
]
}
@@ -1,154 +0,0 @@
<!--
- Copyright (c) 2018-2025, lengleng All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
- Neither the name of the pig4cloud.com developer nor the names of its
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
- Author: lengleng (wangiegie@gmail.com)
-->
<template>
<div class="execution">
<basic-container>
<avue-crud
ref="crud"
:page.sync="page"
:data="tableData"
:permission="permissionList"
:table-loading="tableLoading"
:option="tableOption"
@on-load="getList"
@search-change="searchChange"
@refresh-change="refreshChange"
@size-change="sizeChange"
@current-change="currentChange"
@row-update="handleUpdate"
@row-save="handleSave"
@row-del="handleDel">
<template slot="menuLeft">
<el-button
v-if="permissions.${moduleName}_${pathName}_export"
class="filter-item"
plain
type="primary"
size="small"
icon="el-icon-download"
@click="exportExcel">导出
</el-button>
</template>
</avue-crud>
</basic-container>
</div>
</template>
<script>
import { fetchList, addObj, putObj, delObj } from '@/api/${pathName}'
import { tableOption } from '@/const/crud/${pathName}'
import { mapGetters } from 'vuex'
export default {
name: '${pathName}',
data() {
return {
searchForm: {},
tableData: [],
page: {
total: 0, // 总页数
currentPage: 1, // 当前页数
pageSize: 20 // 每页显示多少条
},
tableLoading: false,
tableOption: tableOption
}
},
computed: {
...mapGetters(['permissions']),
permissionList() {
return {
addBtn: this.vaildData(this.permissions.${moduleName}_${pathName}_add, false),
delBtn: this.vaildData(this.permissions.${moduleName}_${pathName}_del, false),
editBtn: this.vaildData(this.permissions.${moduleName}_${pathName}_edit, false)
}
}
},
methods: {
// 列表查询
getList(page, params) {
this.tableLoading = true
fetchList(Object.assign({
current: page.currentPage,
size: page.pageSize
}, params, this.searchForm)).then(response => {
this.tableData = response.data.data.records
this.page.total = response.data.data.total
this.tableLoading = false
}).catch(() => {
this.tableLoading = false
})
},
// 删除
handleDel: function(row, index) {
this.$confirm('是否确认删除ID为' + row.$pk.lowerAttrName, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(function() {
return delObj(row.$pk.lowerAttrName)
}).then(data => {
this.$message.success('删除成功')
this.getList(this.page)
})
},
// 更新
handleUpdate: function(row, index, done, loading) {
putObj(row).then(data => {
this.$message.success('修改成功')
done()
this.getList(this.page)
}).catch(() => {
loading()
})
},
// 保存
handleSave: function(row, done, loading) {
addObj(row).then(data => {
this.$message.success('添加成功')
done()
this.getList(this.page)
}).catch(() => {
loading()
})
},
// 每页条数改变事件
sizeChange(pageSize) {
this.page.pageSize = pageSize
},
// 当前页发生改变事件
currentChange(current) {
this.page.currentPage = current
},
// 查询事件
searchChange(form, done) {
this.searchForm = form
this.page.currentPage = 1
this.getList(this.page, form)
done()
},
// 刷新事件
refreshChange() {
this.getList(this.page)
},
// 导出excel
exportExcel() {
this.downBlobFile('/${moduleName}/${pathName}/export', this.searchForm, '${pathName}.xlsx')
}
}
}
</script>
@@ -0,0 +1,12 @@
{
"project": {
"packageName": "com.pig4cloud.pigx",
"version": "1.0.0",
"backendPath": "pigx",
"frontendPath": "pigx-ui"
},
"developer": {
"author": "pig",
"email": "sw@mail.pigx.vip"
}
}
@@ -1,56 +0,0 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
import request from '@/router/axios'
export function fetchList(query) {
return request({
url: '/${moduleName}/${pathName}/page',
method: 'get',
params: query
})
}
export function addObj(obj) {
return request({
url: '/${moduleName}/${pathName}',
method: 'post',
data: obj
})
}
export function getObj(id) {
return request({
url: '/${moduleName}/${pathName}/' + id,
method: 'get'
})
}
export function delObj(id) {
return request({
url: '/${moduleName}/${pathName}/' + id,
method: 'delete'
})
}
export function putObj(obj) {
return request({
url: '/${moduleName}/${pathName}',
method: 'put',
data: obj
})
}
@@ -1,92 +0,0 @@
<template>
<el-dialog
:title="!dataForm.id ? '新增' : '修改'"
:close-on-click-modal="false"
append-to-body
:visible.sync="visible">
<el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
#foreach($column in $columns)
#if($column.columnName != $pk.columnName)
<el-form-item label="${column.comments}" prop="${column.lowerAttrName}">
<el-input v-model="dataForm.${column.lowerAttrName}" placeholder="${column.comments}"></el-input>
</el-form-item>
#end
#end
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" @click="dataFormSubmit()" v-if="canSubmit">确定</el-button>
</span>
</el-dialog>
</template>
<script>
import { getObj, addObj, putObj } from '@/api/${pathName}'
export default {
data() {
return {
visible: false,
canSubmit: false,
dataForm: {
#foreach($column in $columns)
#if($column.columnName == $pk.columnName)
${column.lowerAttrName}: 0,
#else
${column.lowerAttrName}: ''#if($velocityCount != $columns.size()),#end
#end
#end
},
dataRule: {
#foreach($column in $columns)
#if($column.columnName != $pk.columnName)
${column.lowerAttrName}: [
{ required: true, message: '${column.comments}不能为空', trigger: 'blur' }
]#if($velocityCount != $columns.size()),#end
#end
#end
}
}
},
methods: {
init(id) {
this.dataForm.${pk.lowerAttrName} = id || 0
this.visible = true
this.canSubmit = true
this.$nextTick(() => {
this.$refs['dataForm'].resetFields()
if (this.dataForm.${pk.lowerAttrName}) {
getObj(this.dataForm.${pk.lowerAttrName}).then(response => {
this.dataForm = response.data.data
})
}
})
},
// 表单提交
dataFormSubmit() {
#[[this.$refs['dataForm'].validate((valid) => {]]#
if (valid) {
this.canSubmit = false
if (this.dataForm.${pk.lowerAttrName}) {
putObj(this.dataForm).then(data => {
this.$notify.success('修改成功')
this.visible = false
this.$emit('refreshDataList')
}).catch(() => {
this.canSubmit = true
})
} else {
addObj(this.dataForm).then(data => {
this.$notify.success('添加成功')
this.visible = false
this.$emit('refreshDataList')
}).catch(() => {
this.canSubmit = true
})
}
}
})
}
}
}
</script>
@@ -1,132 +0,0 @@
<template>
<div class="mod-config">
<basic-container>
<el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
<el-form-item>
<el-button v-if="permissions.${moduleName}_${pathName}_add" icon="el-icon-plus" type="primary" @click="addOrUpdateHandle()">新增</el-button>
<el-button v-if="permissions.${moduleName}_${pathName}_export" icon="el-icon-download" type="primary" plain @click="exportExcel()">导出</el-button>
</el-form-item>
</el-form>
<div class="avue-crud">
<el-table
:data="dataList"
border
v-loading="dataListLoading">
#foreach($column in $columns)
<el-table-column
prop="${column.lowerAttrName}"
header-align="center"
align="center"
label="${column.comments}">
</el-table-column>
#end
<el-table-column
header-align="center"
align="center"
label="操作">
<template slot-scope="scope">
<el-button v-if="permissions.${moduleName}_${pathName}_edit" type="text" size="small" icon="el-icon-edit" @click="addOrUpdateHandle(scope.row.${pk.lowerAttrName})">修改</el-button>
<el-button v-if="permissions.${moduleName}_${pathName}_del" type="text" size="small" icon="el-icon-delete" @click="deleteHandle(scope.row.${pk.lowerAttrName})">删除</el-button>
</template>
</el-table-column>
</el-table>
</div>
<div class="avue-crud__pagination">
<el-pagination
@size-change="sizeChangeHandle"
@current-change="currentChangeHandle"
:current-page="pageIndex"
:page-sizes="[10, 20, 50, 100]"
:page-size="pageSize"
:total="totalPage"
background
layout="total, sizes, prev, pager, next, jumper">
</el-pagination>
</div>
<!-- 弹窗, 新增 / 修改 -->
<table-form v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></table-form>
</basic-container>
</div>
</template>
<script>
import { fetchList, delObj } from '@/api/${pathName}'
import TableForm from './${pathName}-form'
import { mapGetters } from 'vuex'
export default {
data() {
return {
dataForm: {
key: ''
},
searchForm: {},
dataList: [],
pageIndex: 1,
pageSize: 10,
totalPage: 0,
dataListLoading: false,
addOrUpdateVisible: false
}
},
components: {
TableForm
},
computed: {
...mapGetters(['permissions'])
},
created() {
this.getDataList()
},
methods: {
// 获取数据列表
getDataList() {
this.dataListLoading = true
fetchList(Object.assign({
current: this.pageIndex,
size: this.pageSize
})).then(response => {
this.dataList = response.data.data.records
this.totalPage = response.data.data.total
})
this.dataListLoading = false
},
// 每页数
sizeChangeHandle(val) {
this.pageSize = val
this.pageIndex = 1
this.getDataList()
},
// 当前页
currentChangeHandle(val) {
this.pageIndex = val
this.getDataList()
},
// 新增 / 修改
addOrUpdateHandle(id) {
this.addOrUpdateVisible = true
#[[this.$nextTick(() => {]]#
this.$refs.addOrUpdate.init(id)
})
},
// 删除
deleteHandle(id) {
this.$confirm('是否确认删除ID为' + id, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(function() {
return delObj(id)
}).then(data => {
this.$message.success('删除成功')
this.getDataList()
})
},
// 导出excel
exportExcel() {
this.downBlobFile('/${moduleName}/${pathName}/export', this.searchForm, '${pathName}.xlsx')
}
}
}
</script>
@@ -1,6 +0,0 @@
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import response;
import log;
var dbId = new DefaultIdentifierGenerator().nextId(null)
return db.${dsName}.table("${tableName}").primary("$pk.columnName", dbId).save(body)
@@ -1,21 +0,0 @@
import response;
// 判断是否逻辑删除
var logicFlag = false
#foreach($column in $columns)
#if($column.columnName == "del_flag")
logicFlag = true
#end
#end
var result;
if(logicFlag){
result = db.${dsName}.table("${tableName}").primary("$pk.columnName").update({
"$pk.columnName": id,
del_flag: 1
})
}else{
result = db.${dsName}.table("${tableName}").where().eq("$pk.columnName", id).delete()
}
return response.json(result)
@@ -1,4 +0,0 @@
import response;
// 执行DSL 分页输出结果
return response.text("$pk.lowerAttrName")
@@ -1,24 +0,0 @@
import request;
import cn.hutool.json.JSONUtil;
import response;
// 基础查询语句
var queryDsl = db.${dsName}.table("${tableName}")
// 判断是否逻辑删除
#foreach($column in $columns)
#if($column.columnName == "del_flag")
queryDsl = queryDsl.where().eq("del_flag", 0)
#end
#end
// 模糊查询
if (query != null) {
var jsonObj = JSONUtil.parseObj(query)
for (key in jsonObj.keySet()) {
queryDsl.like(key, "%" + jsonObj.get(key) + "%")
}
}
// 执行DSL 分页输出结果
return response.json(queryDsl.page())
@@ -1,5 +0,0 @@
import response;
var data = db.${dsName}.table("${tableName}").primary("$pk.columnName").update(body)
return response.json(data)
@@ -1,25 +0,0 @@
-- 该脚本不要直接执行, 注意维护菜单的父节点ID 默认 父节点-1 , 默认租户 1
#set($menuId=${dateTool.getSystemTime()})
-- 菜单SQL
insert into `sys_menu` ( `menu_id`,`parent_id`, `path`, `permission`, `menu_type`, `icon`, `del_flag`, `create_time`, `sort_order`, `update_time`, `name`, `tenant_id`)
values (${menuId}, '-1', '/${moduleName}/${pathName}/index', '', '0', 'icon-bangzhushouji', '0', null , '8', null , '${comments}管理', 1);
-- 按钮父菜单ID
set @parentId = @@identity;
-- 菜单对应按钮SQL
insert into `sys_menu` ( `menu_id`,`parent_id`, `permission`, `menu_type`, `path`, `icon`, `del_flag`, `create_time`, `sort_order`, `update_time`, `name`, `tenant_id`)
values (${math.add($menuId,1)},${menuId}, '${moduleName}_${pathName}_view', '1', null, '1', '0', null, '0', null, '${comments}查看', 1);
insert into `sys_menu` ( `menu_id`,`parent_id`, `permission`, `menu_type`, `path`, `icon`, `del_flag`, `create_time`, `sort_order`, `update_time`, `name`, `tenant_id`)
values (${math.add($menuId,2)},${menuId}, '${moduleName}_${pathName}_add', '1', null, '1', '0', null, '1', null, '${comments}新增', 1);
insert into `sys_menu` (`menu_id`, `parent_id`, `permission`, `menu_type`, `path`, `icon`, `del_flag`, `create_time`, `sort_order`, `update_time`, `name`, `tenant_id`)
values (${math.add($menuId,3)},${menuId}, '${moduleName}_${pathName}_edit', '1', null, '1', '0', null, '2', null, '${comments}修改', 1);
insert into `sys_menu` (`menu_id`, `parent_id`, `permission`, `menu_type`, `path`, `icon`, `del_flag`, `create_time`, `sort_order`, `update_time`, `name`, `tenant_id`)
values (${math.add($menuId,4)},${menuId}, '${moduleName}_${pathName}_del', '1', null, '1', '0', null, '3', null, '${comments}删除', 1);
insert into `sys_menu` ( `menu_id`,`parent_id`, `permission`, `menu_type`, `path`, `icon`, `del_flag`, `create_time`, `sort_order`, `update_time`, `name`, `tenant_id`)
values (${math.add($menuId,5)},${menuId}, '${moduleName}_${pathName}_export', '1', null, '1', '0', null, '3', null, '导入导出', 1);
@@ -1,18 +0,0 @@
// 以下内容请复制到http.api.js中
pigx${className}: {
// 分页
#[[fetchList: (params={}) => vm.$u.get]]#('/${moduleName}/${pathName}/page',params),
// 新增
#[[addObj: (obj={}) => vm.$u.post]]#('/${moduleName}/${pathName}', obj),
// 修改
#[[putObj: (obj={}) => vm.$u.put]]#('/${moduleName}/${pathName}',obj),
// 删除
#[[delObj: (params) => vm.$u.delete]]#('/${moduleName}/${pathName}/'+params.id),
// 查询
#[[getObj: (params) => vm.$u.get]]#('/${moduleName}/${pathName}/' + params.id)
}
@@ -1,89 +0,0 @@
<template>
<view class="wrap">
<u-form class="form" :model="model" :rules="rules" ref="uForm" label-position="left">
#foreach($column in $columns)
#if($column.columnName != $pk.columnName)
<u-form-item label="${column.comments}" prop="${column.lowerAttrName}" label-width="180">
<u-input v-model="model.${column.lowerAttrName}" placeholder="${column.comments}"></u-input>
</u-form-item>
#end
#end
</u-form>
<view class="form-footer">
<u-button class="btn" type="primary" @click="submit">提交</u-button>
<u-button class="btn" type="default" @click="cancel">关闭</u-button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
type:'',
model: {
#foreach($column in $columns)
#if($column.columnName == $pk.columnName)
${column.lowerAttrName}: 0,
#else
${column.lowerAttrName}: ''#if($velocityCount != $columns.size()),#end
#end
#end
},
rules: {
#foreach($column in $columns)
#if($column.columnName != $pk.columnName)
${column.lowerAttrName}: [
{ required: true, message: '${column.comments}不能为空', trigger: 'blur' }
]#if($velocityCount != $columns.size()),#end
#end
#end
}
}
},
onLoad(params) {
if(params&&params.id!= "undefined"){
this.type = 'edit'
#[[this.$u.api]]#.pigx${className}.getObj(params).then(res => {
this.model = res.data;
});
}else{
this.type = 'add'
this.model = {}
}
},
methods: {
submit() {
#[[this.$refs.uForm.validate(async valid => {]]#
if (valid) {
if(this.type==='edit'){
await #[[this.$u.api]]#.pigx${className}.putObj(this.model)
}else{
await #[[this.$u.api]]#.pigx${className}.addObj(this.model)
}
setTimeout(() => {
uni.showModal({
title: '提示',
ccontent: this.type === 'edit' ? '修改成功' : '添加成功',
showCancel: false,
success: function() {
uni.setStorageSync('refreshList', true);
uni.navigateTo({
url: '/pages/${moduleName}/${pathName}/${pathName}-index'
})
}
})
}, 200)
} else {
#[[this.$u.toast('您填写的信息有误,请根据提示修正。')]]#
}
});
},
cancel() {
uni.navigateBack();
}
}
}
</script>
@@ -1,104 +0,0 @@
<template>
<view class="wrap">
<scroll-view class="scroll-list" scroll-y="true" @scrolltolower="loadMore">
<u-cell-group class="list" :border="false">
<u-card :title="item.${pk.lowerAttrName}" v-for="(item, index) in list" :key="item.${pk.lowerAttrName}"
:index="item.${pk.lowerAttrName}" @click="cardClick(item.${pk.lowerAttrName})">
<view class="" slot="body">
#foreach($column in $columns)
<view class="row-list">
<span class="span-lable">${column.comments}: </span>{{item.${column.lowerAttrName}}}
</view>
#end
</view>
<view class="card-foot" slot="foot">
<u-button type="primary" size="medium" @click="cardClick(item.${pk.lowerAttrName})">编辑</u-button>
<u-button size="medium" @click="del(item.${pk.lowerAttrName})">删除</u-button>
</view>
</u-card>
</u-cell-group>
<view class="loadmore" @click="loadMore">
<u-loadmore :status="loadStatus"></u-loadmore>
</view>
</scroll-view>
<view class="btn-plus" @click="cardClick()">
<u-icon name="plus-circle-fill" size="90" color="#3d87ff"></u-icon>
</view>
</view>
</template>
<script>
export default {
data() {
return {
keywords: '',
query: {
current: 1,
size: 20
},
list: [],
count: 0,
loadStatus: 'loadmore',
options: [{
text: '删除',
style: {
background: '#dd524d'
}
}]
};
},
onLoad() {
this.loadList();
},
onShow() {
if (uni.getStorageSync('refreshList') === true) {
uni.removeStorageSync('refreshList');
this.search('');
}
},
methods: {
cardClick(id) {
uni.navigateTo({
url: '/pages/${moduleName}/${pathName}/${pathName}-form?id='+id
})
},
loadMore() {
this.loadStatus = "loading";
setTimeout(() => {
this.query.current += 1;
this.loadList();
}, 100);
},
loadList() {
#[[this.$u.api]]#.pigx${className}.fetchList(this.query).then(res => {
if (!res.data.records || res.data.records.length == 0) {
this.loadStatus = "nomore";
return;
}
this.list = this.list.concat(res.data.records);
this.total = res.data.total;
this.query.current = res.data.current;
this.query.size = res.data.size;
this.loadStatus = "loadmore";
});
},
del(id) {
let self = this;
uni.showModal({
title: '提示',
content: '确认要删除该数据吗?',
showCancel: true,
success: function(res2) {
if (res2.confirm) {
#[[self.$u.api]]#.pigx${className}.delObj({id:id}).then(res => {
#[[self.$u.toast('删除成功');]]#
self.query.current = 1
self.list = []
self.loadList()
});
}
}
});
}
}
};
</script>
@@ -1,17 +0,0 @@
// 以下内容请复制到pages.json
"pages": [
/**${comments}**/
{
"path": "pages/${moduleName}/${pathName}/${pathName}-index",
"style": {
"navigationBarTitleText": "${comments}"
}
},
{
"path": "pages/${moduleName}/${pathName}/${pathName}-form",
"style": {
"navigationBarTitleText": "${comments}详情"
}
}
}