add 代码生成器模块-后端

V0.5.x
jay 2024-05-28 17:30:30 +08:00
parent 4c13d09f27
commit eafab2a0c1
57 changed files with 5675 additions and 0 deletions

View File

@ -0,0 +1,119 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>iot-module</artifactId>
<groupId>cc.iotkit</groupId>
<version>0.5.3</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>iot-generator</artifactId>
<description>
generator 代码生成
</description>
<properties>
<dynamic-ds.version>3.5.1</dynamic-ds.version>
<mapstruct-plus.lombok.version>0.2.0</mapstruct-plus.lombok.version>
<mybatis-plus.version>3.5.3.1</mybatis-plus.version>
</properties>
<dependencies>
<dependency>
<groupId>cc.iotkit</groupId>
<artifactId>iot-common-core</artifactId>
</dependency>
<dependency>
<groupId>cc.iotkit</groupId>
<artifactId>iot-common-doc</artifactId>
</dependency>
<dependency>
<groupId>cc.iotkit</groupId>
<artifactId>iot-common-log</artifactId>
</dependency>
<!--====================第三方库===================-->
<!--常用工具类 -->
<dependency>
<groupId>com.github.yitter</groupId>
<artifactId>yitter-idgenerator</artifactId>
</dependency>
<!--velocity代码生成使用模板 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
</dependency>
<!-- dynamic-datasource 多数据源-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>${dynamic-ds.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-annotation</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>cc.iotkit</groupId>
<artifactId>iot-common-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source> <!-- depending on your project -->
<target>${java.version}</target> <!-- depending on your project -->
<encoding>utf8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>io.github.linpeilie</groupId>
<artifactId>mapstruct-plus-processor</artifactId>
<version>${mapstruct-plus.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</path>
<!-- other annotation processors -->
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,73 @@
package cc.iotkit.generator.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
*
*
* @author ruoyi
*/
@Component
@ConfigurationProperties(prefix = "gen")
@PropertySource(value = {"classpath:generator.yml"}, encoding = "UTF-8")
public class GenConfig {
/**
*
*/
public static String author;
/**
*
*/
public static String packageName;
/**
* false
*/
public static boolean autoRemovePre;
/**
* ()
*/
public static String tablePrefix;
public static String getAuthor() {
return author;
}
@Value("${author}")
public void setAuthor(String author) {
GenConfig.author = author;
}
public static String getPackageName() {
return packageName;
}
@Value("${packageName}")
public void setPackageName(String packageName) {
GenConfig.packageName = packageName;
}
public static boolean getAutoRemovePre() {
return autoRemovePre;
}
@Value("${autoRemovePre}")
public void setAutoRemovePre(boolean autoRemovePre) {
GenConfig.autoRemovePre = autoRemovePre;
}
public static String getTablePrefix() {
return tablePrefix;
}
@Value("${tablePrefix}")
public void setTablePrefix(String tablePrefix) {
GenConfig.tablePrefix = tablePrefix;
}
}

View File

@ -0,0 +1,102 @@
package cc.iotkit.generator.config;
import cc.iotkit.generator.core.DbIdGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* mybatis-plus()
*
* @author Lion Li
*/
@EnableTransactionManagement(proxyTargetClass = true)
@AutoConfiguration
//@MapperScan("${mybatis-plus.mapperPackage}")
@MapperScan("cc.iotkit.**.mapper")
//@PropertySource(value = "classpath:common-mybatis.yml", factory = YmlPropertySourceFactory.class)
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 数据权限处理
// interceptor.addInnerInterceptor(dataPermissionInterceptor());
// 分页插件
interceptor.addInnerInterceptor(paginationInnerInterceptor());
// 乐观锁插件
interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
return interceptor;
}
/**
*
*/
// public PlusDataPermissionInterceptor dataPermissionInterceptor() {
// return new PlusDataPermissionInterceptor();
// }
/**
*
*/
public PaginationInnerInterceptor paginationInnerInterceptor() {
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
// 设置最大单页限制数量,默认 500 条,-1 不受限制
paginationInnerInterceptor.setMaxLimit(-1L);
// 分页合理化
paginationInnerInterceptor.setOverflow(true);
return paginationInnerInterceptor;
}
/**
*
*/
public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() {
return new OptimisticLockerInnerInterceptor();
}
/**
*
*/
// @Bean
// public MetaObjectHandler metaObjectHandler() {
// return new InjectionMetaObjectHandler();
// }
/**
* 使
* ID
*/
@Bean
public IdentifierGenerator idGenerator() {
// String hostAddress = NetUtil.getLocalhost().getHostAddress();
// TODO: 采用配置文件里的
return new DbIdGenerator((short) 1);
}
/**
* PaginationInnerInterceptor
* https://baomidou.com/pages/97710a/
* OptimisticLockerInnerInterceptor
* https://baomidou.com/pages/0d93c0/
* MetaObjectHandler
* https://baomidou.com/pages/4c6bcf/
* ISqlInjector sql
* https://baomidou.com/pages/42ea4a/
* BlockAttackInnerInterceptor
* https://baomidou.com/pages/f9a237/
* IllegalSQLInnerInterceptor sql(SQL)
* IdentifierGenerator
* https://baomidou.com/pages/568eb2/
* TenantLineInnerInterceptor
* https://baomidou.com/pages/aef2f2/
* DynamicTableNameInnerInterceptor
* https://baomidou.com/pages/2a45ff/
*/
}

View File

@ -0,0 +1,186 @@
package cc.iotkit.generator.constant;
/**
*
*
* @author ruoyi
*/
public interface GenConstants {
/**
*
*/
String TPL_CRUD = "crud";
/**
*
*/
String TPL_TREE = "tree";
/**
*
*/
String TREE_CODE = "treeCode";
/**
*
*/
String TREE_PARENT_CODE = "treeParentCode";
/**
*
*/
String TREE_NAME = "treeName";
/**
* ID
*/
String PARENT_MENU_ID = "parentMenuId";
/**
*
*/
String PARENT_MENU_NAME = "parentMenuName";
/**
*
*/
String[] COLUMNTYPE_STR = {"char", "varchar", "enum", "set", "nchar", "nvarchar", "varchar2", "nvarchar2"};
/**
*
*/
String[] COLUMNTYPE_TEXT = {"tinytext", "text", "mediumtext", "longtext", "binary", "varbinary", "blob",
"ntext", "image", "bytea"};
/**
*
*/
String[] COLUMNTYPE_TIME = {"datetime", "time", "date", "timestamp", "year", "interval",
"smalldatetime", "datetime2", "datetimeoffset"};
/**
*
*/
String[] COLUMNTYPE_NUMBER = {"tinyint", "smallint", "mediumint", "int", "number", "integer",
"bit", "bigint", "float", "double", "decimal", "numeric", "real", "double precision",
"smallserial", "serial", "bigserial", "money", "smallmoney"};
/**
* BO
*/
String[] COLUMNNAME_NOT_ADD = {"create_dept", "create_by", "create_time", "del_flag", "update_by",
"update_time", "version", "tenant_id"};
/**
* BO
*/
String[] COLUMNNAME_NOT_EDIT = {"create_dept", "create_by", "create_time", "del_flag", "update_by",
"update_time", "version", "tenant_id"};
/**
* VO
*/
String[] COLUMNNAME_NOT_LIST = {"create_dept", "create_by", "create_time", "del_flag", "update_by",
"update_time", "version", "tenant_id"};
/**
* BO
*/
String[] COLUMNNAME_NOT_QUERY = {"id", "create_dept", "create_by", "create_time", "del_flag", "update_by",
"update_time", "remark", "version", "tenant_id"};
/**
* Entity
*/
String[] BASE_ENTITY = {"createDept", "createBy", "createTime", "updateBy", "updateTime", "tenantId"};
/**
*
*/
String HTML_INPUT = "input";
/**
*
*/
String HTML_TEXTAREA = "textarea";
/**
*
*/
String HTML_SELECT = "select";
/**
*
*/
String HTML_RADIO = "radio";
/**
*
*/
String HTML_CHECKBOX = "checkbox";
/**
*
*/
String HTML_DATETIME = "datetime";
/**
*
*/
String HTML_IMAGE_UPLOAD = "imageUpload";
/**
*
*/
String HTML_FILE_UPLOAD = "fileUpload";
/**
*
*/
String HTML_EDITOR = "editor";
/**
*
*/
String TYPE_STRING = "String";
/**
*
*/
String TYPE_INTEGER = "Integer";
/**
*
*/
String TYPE_LONG = "Long";
/**
*
*/
String TYPE_DOUBLE = "Double";
/**
*
*/
String TYPE_BIGDECIMAL = "BigDecimal";
/**
*
*/
String TYPE_DATE = "Date";
/**
*
*/
String QUERY_LIKE = "LIKE";
/**
*
*/
String QUERY_EQ = "EQ";
/**
*
*/
String REQUIRE = "1";
}

View File

@ -0,0 +1,213 @@
package cc.iotkit.generator.controller;
import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.api.Request;
import cc.iotkit.common.log.annotation.Log;
import cc.iotkit.common.log.enums.BusinessType;
import cc.iotkit.common.web.core.BaseController;
import cc.iotkit.generator.domain.GenTable;
import cc.iotkit.generator.domain.GenTableColumn;
import cc.iotkit.generator.dto.bo.ImportTableBo;
import cc.iotkit.generator.service.IGenTableService;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
*
* @author Lion Li
*/
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/tool/gen")
public class GenController extends BaseController {
private final IGenTableService genTableService;
/**
*
*/
// @SaCheckPermission("tool:gen:list")
@ApiOperation(value = "查询代码生成列表", notes = "查询代码生成列表,根据查询条件分页")
@PostMapping("/list")
public Paging<GenTable> genList(@RequestBody @Validated PageRequest<GenTable> query) {
return genTableService.selectPageGenTableList(query );
}
/**
*
*
*/
// @SaCheckPermission("tool:gen:query")
@ApiOperation(value = "修改代码生成业务", notes = "修改代码生成业务详情")
@PostMapping(value = "/getDetail")
public Map<String, Object> getInfo(@Validated @RequestBody Request<Long> bo) {
Long tableId = bo.getData();
GenTable table = genTableService.selectGenTableById(tableId);
List<GenTable> tables = genTableService.selectGenTableAll();
List<GenTableColumn> list = genTableService.selectGenTableColumnListByTableId(tableId);
Map<String, Object> map = new HashMap<>();
map.put("info", table);
map.put("rows", list);
map.put("tables", tables);
return map;
}
/**
*
*/
// @SaCheckPermission("tool:gen:list")
@ApiOperation(value = "查询数据库列表", notes = "查询数据库列表")
@PostMapping("/db/list")
public Paging<GenTable> dataList(@RequestBody @Validated PageRequest<GenTable> pageQuery) {
return genTableService.selectPageDbTableList( pageQuery);
}
/**
*
*
* @param tableId ID
*/
// @SaCheckPermission("tool:gen:list")
@ApiOperation(value = "查询数据表字段列表", notes = "查询数据表字段列表")
@PostMapping(value = "/column/{tableId}")
public Paging<GenTableColumn> columnList(Long tableId) {
List<GenTableColumn> list = genTableService.selectGenTableColumnListByTableId(tableId);
return new Paging<>();
}
/**
*
*
*/
// @SaCheckPermission("tool:gen:import")
@Log(title = "代码生成", businessType = BusinessType.IMPORT)
@PostMapping("/importTable")
@ApiOperation(value = "导入表结构(保存)", notes = "导入表结构(保存)")
public void importTableSave(@Validated @RequestBody Request<ImportTableBo> bo) {
List<String> tables = bo.getData().getTables();
// 查询表信息
List<GenTable> tableList = genTableService.selectDbTableListByNames(tables);
genTableService.importGenTable(tableList);
}
/**
*
*/
// @SaCheckPermission("tool:gen:edit")
@ApiOperation(value = "修改保存代码生成业务", notes = "修改保存代码生成业务")
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
public void editSave(@Validated @RequestBody Request<GenTable> bo) {
GenTable genTable = bo.getData();
genTableService.validateEdit(genTable);
genTableService.updateGenTable(genTable);
}
/**
*
*
*/
// @SaCheckPermission("tool:gen:remove")
@Log(title = "代码生成", businessType = BusinessType.DELETE)
@PostMapping("/delete")
@ApiOperation(value = "删除代码生成", notes = "删除代码生成")
public void remove(@Validated @RequestBody Request<List<Long>> bo) {
genTableService.deleteGenTableByIds(bo.getData());
}
/**
*
*
*/
// @SaCheckPermission("tool:gen:preview")
@ApiOperation(value = "预览代码", notes = "预览代码")
@PostMapping("/preview")
public Map<String, String> preview(@Validated @RequestBody Request<Long> bo) throws IOException {
Map<String, String> dataMap = genTableService.previewCode(bo.getData());
return dataMap;
}
/**
*
*
* @param tableName
*/
// @SaCheckPermission("tool:gen:code")
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
@PostMapping("/download/{tableName}")
public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
byte[] data = genTableService.downloadCode(tableName);
genCode(response, data);
}
/**
*
*
* @param tableName
*/
// @SaCheckPermission("tool:gen:code")
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
@ApiOperation(value = "生成代码(自定义路径)", notes = "生成代码(自定义路径)")
@PostMapping("/genCode/{tableName}")
public void genCode(@PathVariable("tableName") String tableName) {
genTableService.generatorCode(tableName);
}
/**
*
*
*/
// @SaCheckPermission("tool:gen:edit")
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
@ApiOperation(value = "同步数据库", notes = "同步数据库")
@PostMapping("/synchDb")
public void synchDb(@Validated @RequestBody Request<String> bo) {
genTableService.synchDb(bo.getData());
}
/**
*
*
* @param tables
*/
// @SaCheckPermission("tool:gen:code")
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
@ApiOperation(value = "批量生成代码", notes = "批量生成代码")
@PostMapping("/batchGenCode")
public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
String[] tableNames = Convert.toStrArray(tables);
byte[] data = genTableService.downloadCode(tableNames);
genCode(response, data);
}
/**
* zip
*/
private void genCode(HttpServletResponse response, byte[] data) throws IOException {
response.reset();
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), false, data);
}
}

View File

@ -0,0 +1,70 @@
package cc.iotkit.generator.core;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Entity
*
* @author Lion Li
*/
@Data
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@JsonIgnore
@TableField(exist = false)
private String searchValue;
/**
*
*/
@TableField(fill = FieldFill.INSERT)
private Long createDept;
/**
*
*/
@TableField(fill = FieldFill.INSERT)
private Long createBy;
/**
*
*/
@TableField(fill = FieldFill.INSERT)
private Date createTime;
/**
*
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateBy;
/**
*
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
/**
*
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@TableField(exist = false)
private Map<String, Object> params = new HashMap<>();
}

View File

@ -0,0 +1,198 @@
package cc.iotkit.generator.core;
import cc.iotkit.common.utils.MapstructUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Mapper ,
*
* @param <T> table
* @param <V> vo
* @author Lion Li
* @since 2021-05-13
*/
@SuppressWarnings("unchecked")
public interface BaseMapperPlus<T, V> extends BaseMapper<T> {
Log log = LogFactory.getLog(BaseMapperPlus.class);
default Class<V> currentVoClass() {
return (Class<V>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseMapperPlus.class, 1);
}
default Class<T> currentModelClass() {
return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseMapperPlus.class, 0);
}
default List<T> selectList() {
return this.selectList(new QueryWrapper<>());
}
/**
*
*/
default boolean insertBatch(Collection<T> entityList) {
return Db.saveBatch(entityList);
}
/**
*
*/
default boolean updateBatchById(Collection<T> entityList) {
return Db.updateBatchById(entityList);
}
/**
*
*/
default boolean insertOrUpdateBatch(Collection<T> entityList) {
return Db.saveOrUpdateBatch(entityList);
}
/**
* ()
*/
default boolean insertBatch(Collection<T> entityList, int batchSize) {
return Db.saveBatch(entityList, batchSize);
}
/**
* ()
*/
default boolean updateBatchById(Collection<T> entityList, int batchSize) {
return Db.updateBatchById(entityList, batchSize);
}
/**
* ()
*/
default boolean insertOrUpdateBatch(Collection<T> entityList, int batchSize) {
return Db.saveOrUpdateBatch(entityList, batchSize);
}
/**
* ()
*/
default boolean insertOrUpdate(T entity) {
return Db.saveOrUpdate(entity);
}
default V selectVoById(Serializable id) {
return selectVoById(id, this.currentVoClass());
}
/**
* ID
*/
default <C> C selectVoById(Serializable id, Class<C> voClass) {
T obj = this.selectById(id);
if (ObjectUtil.isNull(obj)) {
return null;
}
return MapstructUtils.convert(obj, voClass);
}
default List<V> selectVoBatchIds(Collection<? extends Serializable> idList) {
return selectVoBatchIds(idList, this.currentVoClass());
}
/**
* ID
*/
default <C> List<C> selectVoBatchIds(Collection<? extends Serializable> idList, Class<C> voClass) {
List<T> list = this.selectBatchIds(idList);
if (CollUtil.isEmpty(list)) {
return CollUtil.newArrayList();
}
return MapstructUtils.convert(list, voClass);
}
default List<V> selectVoByMap(Map<String, Object> map) {
return selectVoByMap(map, this.currentVoClass());
}
/**
* columnMap
*/
default <C> List<C> selectVoByMap(Map<String, Object> map, Class<C> voClass) {
List<T> list = this.selectByMap(map);
if (CollUtil.isEmpty(list)) {
return CollUtil.newArrayList();
}
return MapstructUtils.convert(list, voClass);
}
default V selectVoOne(Wrapper<T> wrapper) {
return selectVoOne(wrapper, this.currentVoClass());
}
/**
* entity
*/
default <C> C selectVoOne(Wrapper<T> wrapper, Class<C> voClass) {
T obj = this.selectOne(wrapper);
if (ObjectUtil.isNull(obj)) {
return null;
}
return MapstructUtils.convert(obj, voClass);
}
default List<V> selectVoList() {
return selectVoList(new QueryWrapper<>(), this.currentVoClass());
}
default List<V> selectVoList(Wrapper<T> wrapper) {
return selectVoList(wrapper, this.currentVoClass());
}
/**
* entity
*/
default <C> List<C> selectVoList(Wrapper<T> wrapper, Class<C> voClass) {
List<T> list = this.selectList(wrapper);
if (CollUtil.isEmpty(list)) {
return CollUtil.newArrayList();
}
return MapstructUtils.convert(list, voClass);
}
default <P extends IPage<V>> P selectVoPage(IPage<T> page, Wrapper<T> wrapper) {
return selectVoPage(page, wrapper, this.currentVoClass());
}
/**
* VO
*/
default <C, P extends IPage<C>> P selectVoPage(IPage<T> page, Wrapper<T> wrapper, Class<C> voClass) {
IPage<T> pageData = this.selectPage(page, wrapper);
IPage<C> voPage = new Page<>(pageData.getCurrent(), pageData.getSize(), pageData.getTotal());
if (CollUtil.isEmpty(pageData.getRecords())) {
return (P) voPage;
}
voPage.setRecords(MapstructUtils.convert(pageData.getRecords(), voClass));
return (P) voPage;
}
default <C> List<C> selectObjs(Wrapper<T> wrapper, Function<? super Object, C> mapper) {
return this.selectObjs(wrapper).stream().filter(Objects::nonNull).map(mapper).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,76 @@
package cc.iotkit.generator.core;
import cc.iotkit.common.exception.BizException;
import cc.iotkit.common.utils.SpringUtils;
import cn.hutool.core.convert.Convert;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
/**
*
*
* @author Lion Li
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DataBaseHelper {
private static final DynamicRoutingDataSource DS = SpringUtils.getBean(DynamicRoutingDataSource.class);
/**
*
*/
public static DataBaseType getDataBaseType() {
DataSource dataSource = DS.determineDataSource();
try (Connection conn = dataSource.getConnection()) {
DatabaseMetaData metaData = conn.getMetaData();
String databaseProductName = metaData.getDatabaseProductName();
return DataBaseType.find(databaseProductName);
} catch (SQLException e) {
throw new BizException(e.getMessage());
}
}
public static boolean isMySql() {
return DataBaseType.MY_SQL == getDataBaseType();
}
public static boolean isH2() {
return DataBaseType.H2 == getDataBaseType();
}
public static boolean isOracle() {
return DataBaseType.ORACLE == getDataBaseType();
}
public static boolean isPostgerSql() {
return DataBaseType.POSTGRE_SQL == getDataBaseType();
}
public static boolean isSqlServer() {
return DataBaseType.SQL_SERVER == getDataBaseType();
}
public static String findInSet(Object var1, String var2) {
DataBaseType dataBasyType = getDataBaseType();
String var = Convert.toStr(var1);
if (dataBasyType == DataBaseType.SQL_SERVER) {
// charindex(',100,' , ',0,100,101,') <> 0
return String.format("charindex(',%s,' , ','+%s+',') <> 0",var, var2 );
} else if (dataBasyType == DataBaseType.POSTGRE_SQL) {
// (select position(',100,' in ',0,100,101,')) <> 0
return String.format("(select position(',%s,' in ','||%s||',')) <> 0", var, var2);
} else if (dataBasyType == DataBaseType.ORACLE) {
// instr(',0,100,101,' , ',100,') <> 0
return String.format("instr(','||%s||',' , ',%s,') <> 0",var2, var );
}
// find_in_set(100 , '0,100,101')
return String.format("find_in_set('%s' , %s) <> 0", var, var2);
}
}

View File

@ -0,0 +1,51 @@
package cc.iotkit.generator.core;
import cc.iotkit.common.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
*
*
* @author Lion Li
*/
@Getter
@AllArgsConstructor
public enum DataBaseType {
/**
* MySQL
*/
MY_SQL("MySQL"),
H2("H2"),
/**
* Oracle
*/
ORACLE("Oracle"),
/**
* PostgreSQL
*/
POSTGRE_SQL("PostgreSQL"),
/**
* SQL Server
*/
SQL_SERVER("Microsoft SQL Server");
private final String type;
public static DataBaseType find(String databaseProductName) {
if (StringUtils.isBlank(databaseProductName)) {
return null;
}
for (DataBaseType type : values()) {
if (type.getType().equals(databaseProductName)) {
return type;
}
}
return null;
}
}

View File

@ -0,0 +1,30 @@
package cc.iotkit.generator.core;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.github.yitter.contract.IdGeneratorOptions;
import com.github.yitter.idgen.YitIdHelper;
/**
* @author: Jay
* @description:
* @date:created in 2023/5/18 10:20
* @modificed by:
*/
public class DbIdGenerator implements IdentifierGenerator {
public DbIdGenerator(Short workerId) {
// 使用网卡信息绑定雪花生成器
// 防止集群雪花ID重复
IdGeneratorOptions options = new IdGeneratorOptions(workerId);
YitIdHelper.setIdGenerator(options);
}
@Override
public Number nextId(Object entity) {
return YitIdHelper.nextId();
}
}

View File

@ -0,0 +1,25 @@
package cc.iotkit.generator.core;
import cc.iotkit.common.api.PageRequest;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.io.Serializable;
/**
*
*
* @author Lion Li
*/
public class PageBuilder implements Serializable {
public static Page build(PageRequest pageRequest) {
Integer pageNum = ObjectUtil.defaultIfNull(pageRequest.getPageNum(), PageQuery.DEFAULT_PAGE_NUM);
Integer pageSize = ObjectUtil.defaultIfNull(pageRequest.getPageSize(), PageQuery.DEFAULT_PAGE_SIZE);
return new Page(pageNum, pageSize);
}
}

View File

@ -0,0 +1,113 @@
package cc.iotkit.generator.core;
import cc.iotkit.common.exception.BizException;
import cc.iotkit.common.utils.StringUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
*
*
* @author Lion Li
*/
@Data
public class PageQuery implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
private Integer pageSize;
/**
*
*/
private Integer pageNum;
/**
*
*/
private String orderByColumn;
/**
* descasc
*/
private String isAsc;
/**
*
*/
public static final int DEFAULT_PAGE_NUM = 1;
/**
*
*/
public static final int DEFAULT_PAGE_SIZE = Integer.MAX_VALUE;
public <T> Page<T> build() {
Integer pageNum = ObjectUtil.defaultIfNull(getPageNum(), DEFAULT_PAGE_NUM);
Integer pageSize = ObjectUtil.defaultIfNull(getPageSize(), DEFAULT_PAGE_SIZE);
if (pageNum <= 0) {
pageNum = DEFAULT_PAGE_NUM;
}
Page<T> page = new Page<>(pageNum, pageSize);
List<OrderItem> orderItems = buildOrderItem();
if (CollUtil.isNotEmpty(orderItems)) {
page.addOrder(orderItems);
}
return page;
}
/**
*
*
* :
* {isAsc:"asc",orderByColumn:"id"} order by id asc
* {isAsc:"asc",orderByColumn:"id,createTime"} order by id asc,create_time asc
* {isAsc:"desc",orderByColumn:"id,createTime"} order by id desc,create_time desc
* {isAsc:"asc,desc",orderByColumn:"id,createTime"} order by id asc,create_time desc
*/
private List<OrderItem> buildOrderItem() {
if (StringUtils.isBlank(orderByColumn) || StringUtils.isBlank(isAsc)) {
return Collections.emptyList();
}
String orderBy = SqlUtil.escapeOrderBySql(orderByColumn);
orderBy = StringUtils.toUnderScoreCase(orderBy);
// 兼容前端排序类型
isAsc = StringUtils.replaceEach(isAsc, new String[]{"ascending", "descending"}, new String[]{"asc", "desc"});
String[] orderByArr = orderBy.split(StringUtils.SEPARATOR);
String[] isAscArr = isAsc.split(StringUtils.SEPARATOR);
if (isAscArr.length != 1 && isAscArr.length != orderByArr.length) {
throw new BizException("排序参数有误");
}
List<OrderItem> list = new ArrayList<>();
// 每个字段各自排序
for (int i = 0; i < orderByArr.length; i++) {
String orderByStr = orderByArr[i];
String isAscStr = isAscArr.length == 1 ? isAscArr[0] : isAscArr[i];
if ("asc".equals(isAscStr)) {
list.add(OrderItem.asc(orderByStr));
} else if ("desc".equals(isAscStr)) {
list.add(OrderItem.desc(orderByStr));
} else {
throw new BizException("排序参数有误");
}
}
return list;
}
}

View File

@ -0,0 +1,58 @@
package cc.iotkit.generator.core;
import cc.iotkit.common.utils.StringUtils;
import cn.hutool.core.exceptions.UtilException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* sql
*
* @author ruoyi
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SqlUtil {
/**
* sql
*/
public static final String SQL_REGEX = "select |insert |delete |update |drop |count |exec |chr |mid |master |truncate |char |and |declare ";
/**
* 线
*/
public static final String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+";
/**
*
*/
public static String escapeOrderBySql(String value) {
if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) {
throw new UtilException("参数不符合规范,不能进行查询");
}
return value;
}
/**
* order by
*/
public static boolean isValidOrderBySql(String value) {
return value.matches(SQL_PATTERN);
}
/**
* SQL
*/
public static void filterKeyword(String value) {
if (StringUtils.isEmpty(value)) {
return;
}
String[] sqlKeywords = StringUtils.split(SQL_REGEX, "\\|");
for (String sqlKeyword : sqlKeywords) {
if (StringUtils.indexOfIgnoreCase(value, sqlKeyword) > -1) {
throw new UtilException("参数存在SQL注入风险");
}
}
}
}

View File

@ -0,0 +1,196 @@
package cc.iotkit.generator.domain;
import cc.iotkit.common.utils.StringUtils;
import cc.iotkit.generator.constant.GenConstants;
import cc.iotkit.generator.core.BaseEntity;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
/**
* gen_table
*
* @author Lion Li
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("gen_table")
public class GenTable extends BaseEntity {
/**
*
*/
@TableId(value = "table_id")
private Long tableId;
/**
*
*/
@NotBlank(message = "数据源名称不能为空")
private String dataName;
/**
*
*/
@NotBlank(message = "表名称不能为空")
private String tableName;
/**
*
*/
@NotBlank(message = "表描述不能为空")
private String tableComment;
/**
*
*/
private String subTableName;
/**
*
*/
private String subTableFkName;
/**
* ()
*/
@NotBlank(message = "实体类名称不能为空")
private String className;
/**
* 使crud tree sub
*/
private String tplCategory;
/**
*
*/
@NotBlank(message = "生成包路径不能为空")
private String packageName;
/**
*
*/
@NotBlank(message = "生成模块名不能为空")
private String moduleName;
/**
*
*/
@NotBlank(message = "生成业务名不能为空")
private String businessName;
/**
*
*/
@NotBlank(message = "生成功能名不能为空")
private String functionName;
/**
*
*/
@NotBlank(message = "作者不能为空")
private String functionAuthor;
/**
* 0zip 1
*/
private String genType;
/**
*
*/
@TableField(updateStrategy = FieldStrategy.NOT_EMPTY)
private String genPath;
/**
*
*/
@TableField(exist = false)
private GenTableColumn pkColumn;
/**
*
*/
@Valid
@TableField(exist = false)
private List<GenTableColumn> columns;
/**
*
*/
private String options;
/**
*
*/
private String remark;
/**
*
*/
@TableField(exist = false)
private String treeCode;
/**
*
*/
@TableField(exist = false)
private String treeParentCode;
/**
*
*/
@TableField(exist = false)
private String treeName;
/*
* id
*/
@TableField(exist = false)
private List<Long> menuIds;
/**
* ID
*/
@TableField(exist = false)
private String parentMenuId;
/**
*
*/
@TableField(exist = false)
private String parentMenuName;
public boolean isTree() {
return isTree(this.tplCategory);
}
public static boolean isTree(String tplCategory) {
return tplCategory != null && StringUtils.equals(GenConstants.TPL_TREE, tplCategory);
}
public boolean isCrud() {
return isCrud(this.tplCategory);
}
public static boolean isCrud(String tplCategory) {
return tplCategory != null && StringUtils.equals(GenConstants.TPL_CRUD, tplCategory);
}
public boolean isSuperColumn(String javaField) {
return isSuperColumn(this.tplCategory, javaField);
}
public static boolean isSuperColumn(String tplCategory, String javaField) {
return StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY);
}
}

View File

@ -0,0 +1,222 @@
package cc.iotkit.generator.domain;
import cc.iotkit.common.utils.StringUtils;
import cc.iotkit.generator.core.BaseEntity;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.ibatis.type.JdbcType;
/**
* gen_table_column
*
* @author Lion Li
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("gen_table_column")
public class GenTableColumn extends BaseEntity {
/**
*
*/
@TableId(value = "column_id")
private Long columnId;
/**
*
*/
private Long tableId;
/**
*
*/
private String columnName;
/**
*
*/
@TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR)
private String columnComment;
/**
*
*/
private String columnType;
/**
* JAVA
*/
private String javaType;
/**
* JAVA
*/
@NotBlank(message = "Java属性不能为空")
private String javaField;
/**
* 1
*/
@TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR)
private String isPk;
/**
* 1
*/
@TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR)
private String isIncrement;
/**
* 1
*/
@TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR)
private String isRequired;
/**
* 1
*/
@TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR)
private String isInsert;
/**
* 1
*/
@TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR)
private String isEdit;
/**
* 1
*/
@TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR)
private String isList;
/**
* 1
*/
@TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR)
private String isQuery;
/**
* EQNEGTLTLIKEBETWEEN
*/
private String queryType;
/**
* inputtextareaselectcheckboxradiodatetimeimageuploadeditor
*/
private String htmlType;
/**
*
*/
private String dictType;
/**
*
*/
private Integer sort;
public String getCapJavaField() {
return StringUtils.capitalize(javaField);
}
public boolean isPk() {
return isPk(this.isPk);
}
public boolean isPk(String isPk) {
return isPk != null && StringUtils.equals("1", isPk);
}
public boolean isIncrement() {
return isIncrement(this.isIncrement);
}
public boolean isIncrement(String isIncrement) {
return isIncrement != null && StringUtils.equals("1", isIncrement);
}
public boolean isRequired() {
return isRequired(this.isRequired);
}
public boolean isRequired(String isRequired) {
return isRequired != null && StringUtils.equals("1", isRequired);
}
public boolean isInsert() {
return isInsert(this.isInsert);
}
public boolean isInsert(String isInsert) {
return isInsert != null && StringUtils.equals("1", isInsert);
}
public boolean isEdit() {
return isInsert(this.isEdit);
}
public boolean isEdit(String isEdit) {
return isEdit != null && StringUtils.equals("1", isEdit);
}
public boolean isList() {
return isList(this.isList);
}
public boolean isList(String isList) {
return isList != null && StringUtils.equals("1", isList);
}
public boolean isQuery() {
return isQuery(this.isQuery);
}
public boolean isQuery(String isQuery) {
return isQuery != null && StringUtils.equals("1", isQuery);
}
public boolean isSuperColumn() {
return isSuperColumn(this.javaField);
}
public static boolean isSuperColumn(String javaField) {
return StringUtils.equalsAnyIgnoreCase(javaField,
// BaseEntity
"createBy", "createTime", "updateBy", "updateTime",
// TreeEntity
"parentName", "parentId");
}
public boolean isUsableColumn() {
return isUsableColumn(javaField);
}
public static boolean isUsableColumn(String javaField) {
// isSuperColumn()中的名单用于避免生成多余Domain属性若某些属性在生成页面时需要用到不能忽略则放在此处白名单
return StringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum", "remark");
}
public String readConverterExp() {
String remarks = StringUtils.substringBetween(this.columnComment, "", "");
StringBuffer sb = new StringBuffer();
if (StringUtils.isNotEmpty(remarks)) {
for (String value : remarks.split(" ")) {
if (StringUtils.isNotEmpty(value)) {
Object startStr = value.subSequence(0, 1);
String endStr = value.substring(1);
sb.append(StringUtils.EMPTY).append(startStr).append("=").append(endStr).append(StringUtils.SEPARATOR);
}
}
return sb.deleteCharAt(sb.length() - 1).toString();
} else {
return this.columnComment;
}
}
}

View File

@ -0,0 +1,24 @@
package cc.iotkit.generator.dto.bo;
import cc.iotkit.common.api.BaseDto;
import io.swagger.annotations.ApiModelProperty;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* @Author: jay
* @Date: 2023/6/24 16:47
* @Version: V1.0
* @Description: Bo
*/
@Data
public class ImportTableBo extends BaseDto {
@ApiModelProperty(value = "表名列表", notes = "表名列表")
@NotEmpty(message = "表名列表不能为空")
private List<String> tables;
}

View File

@ -0,0 +1,32 @@
package cc.iotkit.generator.factory;
import cc.iotkit.common.utils.StringUtils;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import java.io.IOException;
/**
* yml
*
* @author Lion Li
*/
public class YmlPropertySourceFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
String sourceName = resource.getResource().getFilename();
if (StringUtils.isNotBlank(sourceName) && StringUtils.endsWithAny(sourceName, ".yml", ".yaml")) {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return new PropertiesPropertySource(sourceName, factory.getObject());
}
return super.createPropertySource(name, resource);
}
}

View File

@ -0,0 +1,24 @@
package cc.iotkit.generator.mapper;
import cc.iotkit.generator.core.BaseMapperPlus;
import cc.iotkit.generator.domain.GenTableColumn;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import java.util.List;
/**
*
*
* @author Lion Li
*/
@InterceptorIgnore(dataPermission = "true", tenantLine = "true")
public interface GenTableColumnMapper extends BaseMapperPlus<GenTableColumn, GenTableColumn> {
/**
*
*
* @param tableName
* @return
*/
List<GenTableColumn> selectDbTableColumnsByName(String tableName);
}

View File

@ -0,0 +1,63 @@
package cc.iotkit.generator.mapper;
import cc.iotkit.generator.core.BaseMapperPlus;
import cc.iotkit.generator.domain.GenTable;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import java.util.Collection;
import java.util.List;
/**
*
*
* @author Lion Li
*/
@InterceptorIgnore( tenantLine = "true")
public interface GenTableMapper extends BaseMapperPlus<GenTable, GenTable> {
/**
*
*
* @param genTable
* @return
*/
@InterceptorIgnore( tenantLine = "true")
Page<GenTable> selectPageDbTableList(@Param("page") Page<GenTable> page, @Param("genTable") GenTable genTable);
/**
*
*
* @param tableNames
* @return
*/
List<GenTable> selectDbTableListByNames(Collection<String> tableNames);
/**
*
*
* @return
*/
List<GenTable> selectGenTableAll();
/**
* ID
*
* @param id ID
* @return
*/
GenTable selectGenTableById(Long id);
/**
*
*
* @param tableName
* @return
*/
GenTable selectGenTableByName(String tableName);
List<String> selectTableNameList(String dataName);
}

View File

@ -0,0 +1,463 @@
package cc.iotkit.generator.service;
import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.constant.Constants;
import cc.iotkit.common.exception.BizException;
import cc.iotkit.common.satoken.utils.LoginHelper;
import cc.iotkit.common.utils.JsonUtils;
import cc.iotkit.common.utils.StreamUtils;
import cc.iotkit.common.utils.StringUtils;
import cc.iotkit.common.utils.file.FileUtils;
import cc.iotkit.generator.constant.GenConstants;
import cc.iotkit.generator.core.DbIdGenerator;
import cc.iotkit.generator.core.PageBuilder;
import cc.iotkit.generator.domain.GenTable;
import cc.iotkit.generator.domain.GenTableColumn;
import cc.iotkit.generator.mapper.GenTableColumnMapper;
import cc.iotkit.generator.mapper.GenTableMapper;
import cc.iotkit.generator.util.GenUtils;
import cc.iotkit.generator.util.VelocityInitializer;
import cc.iotkit.generator.util.VelocityUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
*
*
* @author Lion Li
*/
@DS("#header.datasource")
@Slf4j
@RequiredArgsConstructor
@Service
public class GenTableServiceImpl implements IGenTableService {
private final GenTableMapper baseMapper;
private final GenTableColumnMapper genTableColumnMapper;
private final DbIdGenerator identifierGenerator;
/**
*
*
* @param tableId
* @return
*/
@Override
public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId) {
return genTableColumnMapper.selectList(new LambdaQueryWrapper<GenTableColumn>()
.eq(GenTableColumn::getTableId, tableId)
.orderByAsc(GenTableColumn::getSort));
}
/**
*
*
* @param id ID
* @return
*/
@Override
public GenTable selectGenTableById(Long id) {
GenTable genTable = baseMapper.selectGenTableById(id);
setTableFromOptions(genTable);
return genTable;
}
@Override
public Paging<GenTable> selectPageGenTableList( PageRequest<GenTable> pageQuery) {
Page<GenTable> page = baseMapper.selectPage(PageBuilder.build(pageQuery), this.buildGenTableQueryWrapper(pageQuery.getData()));
return new Paging<>(page.getTotal(), page.getRecords());
}
private QueryWrapper<GenTable> buildGenTableQueryWrapper(GenTable genTable) {
Map<String, Object> params = genTable.getParams();
QueryWrapper<GenTable> wrapper = Wrappers.query();
wrapper.like(StringUtils.isNotBlank(genTable.getTableName()), "lower(table_name)", StringUtils.lowerCase(genTable.getTableName()))
.like(StringUtils.isNotBlank(genTable.getTableComment()), "lower(table_comment)", StringUtils.lowerCase(genTable.getTableComment()))
.between(StringUtils.isNotBlank((CharSequence) params.get("beginTime")) && StringUtils.isNotBlank((CharSequence) params.get("endTime")),
"create_time", params.get("beginTime"), params.get("endTime"));
return wrapper;
}
@Override
public Paging<GenTable> selectPageDbTableList(PageRequest<GenTable> pageQuery) {
GenTable genTable = pageQuery.getData();
genTable.getParams().put("genTableNames",baseMapper.selectTableNameList(genTable.getDataName()));
Page<GenTable> page = baseMapper.selectPageDbTableList(PageBuilder.build(pageQuery), genTable);
return new Paging<>(page.getTotal(), page.getRecords());
}
/**
*
*
* @param tableNames
* @return
*/
@Override
public List<GenTable> selectDbTableListByNames(Collection<String> tableNames) {
return baseMapper.selectDbTableListByNames(tableNames);
}
/**
*
*
* @return
*/
@Override
public List<GenTable> selectGenTableAll() {
return baseMapper.selectGenTableAll();
}
/**
*
*
* @param genTable
* @return
*/
@Transactional(rollbackFor = Exception.class)
@Override
public void updateGenTable(GenTable genTable) {
String options = JsonUtils.toJsonString(genTable.getParams());
genTable.setOptions(options);
int row = baseMapper.updateById(genTable);
if (row > 0) {
for (GenTableColumn cenTableColumn : genTable.getColumns()) {
genTableColumnMapper.updateById(cenTableColumn);
}
}
}
/**
*
*
* @param tableIds ID
* @return
*/
@Transactional(rollbackFor = Exception.class)
@Override
public void deleteGenTableByIds(Collection<Long> tableIds) {
baseMapper.deleteBatchIds(tableIds);
genTableColumnMapper.delete(new LambdaQueryWrapper<GenTableColumn>().in(GenTableColumn::getTableId, tableIds));
}
/**
*
*
* @param tableList
*/
@Transactional(rollbackFor = Exception.class)
@Override
public void importGenTable(List<GenTable> tableList) {
String operName = LoginHelper.getUsername();
try {
for (GenTable table : tableList) {
String tableName = table.getTableName();
GenUtils.initTable(table, operName);
int row = baseMapper.insert(table);
if (row > 0) {
// 保存列信息
List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
List<GenTableColumn> saveColumns = new ArrayList<>();
for (GenTableColumn column : genTableColumns) {
GenUtils.initColumnField(column, table);
saveColumns.add(column);
}
if (CollUtil.isNotEmpty(saveColumns)) {
genTableColumnMapper.insertBatch(saveColumns);
}
}
}
} catch (Exception e) {
throw new BizException("导入失败:" + e.getMessage());
}
}
/**
*
*
* @param tableId
* @return
*/
@Override
public Map<String, String> previewCode(Long tableId) {
Map<String, String> dataMap = new LinkedHashMap<>();
// 查询表信息
GenTable table = baseMapper.selectGenTableById(tableId);
List<Long> menuIds = new ArrayList<>();
for (int i = 0; i < 6; i++) {
menuIds.add((Long) identifierGenerator.nextId(null));
}
table.setMenuIds(menuIds);
// 设置主键列信息
setPkColumn(table);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
dataMap.put(template, sw.toString());
}
return dataMap;
}
/**
*
*
* @param tableName
* @return
*/
@Override
public byte[] downloadCode(String tableName) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
generatorCode(tableName, zip);
IoUtil.close(zip);
return outputStream.toByteArray();
}
/**
*
*
* @param tableName
*/
@Override
public void generatorCode(String tableName) {
// 查询表信息
GenTable table = baseMapper.selectGenTableByName(tableName);
// 设置主键列信息
setPkColumn(table);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) {
if (!StringUtils.containsAny(template, "sql.vm", "api.ts.vm", "types.ts.vm", "index.vue.vm", "index-tree.vue.vm")) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
try {
String path = getGenPath(table, template);
FileUtils.writeUtf8String(sw.toString(), path);
} catch (Exception e) {
throw new BizException("渲染模板失败,表名:" + table.getTableName());
}
}
}
}
/**
*
*
* @param tableName
*/
@Transactional(rollbackFor = Exception.class)
@Override
public void synchDb(String tableName) {
GenTable table = baseMapper.selectGenTableByName(tableName);
List<GenTableColumn> tableColumns = table.getColumns();
Map<String, GenTableColumn> tableColumnMap = StreamUtils.toIdentityMap(tableColumns, GenTableColumn::getColumnName);
List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
if (CollUtil.isEmpty(dbTableColumns)) {
throw new BizException("同步数据失败,原表结构不存在");
}
List<String> dbTableColumnNames = StreamUtils.toList(dbTableColumns, GenTableColumn::getColumnName);
List<GenTableColumn> saveColumns = new ArrayList<>();
dbTableColumns.forEach(column -> {
GenUtils.initColumnField(column, table);
if (tableColumnMap.containsKey(column.getColumnName())) {
GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName());
column.setColumnId(prevColumn.getColumnId());
if (column.isList()) {
// 如果是列表,继续保留查询方式/字典类型选项
column.setDictType(prevColumn.getDictType());
column.setQueryType(prevColumn.getQueryType());
}
if (StringUtils.isNotEmpty(prevColumn.getIsRequired()) && !column.isPk()
&& (column.isInsert() || column.isEdit())
&& ((column.isUsableColumn()) || (!column.isSuperColumn()))) {
// 如果是(新增/修改&非主键/非忽略及父属性),继续保留必填/显示类型选项
column.setIsRequired(prevColumn.getIsRequired());
column.setHtmlType(prevColumn.getHtmlType());
}
}
saveColumns.add(column);
});
if (CollUtil.isNotEmpty(saveColumns)) {
genTableColumnMapper.insertOrUpdateBatch(saveColumns);
}
List<GenTableColumn> delColumns = StreamUtils.filter(tableColumns, column -> !dbTableColumnNames.contains(column.getColumnName()));
if (CollUtil.isNotEmpty(delColumns)) {
List<Long> ids = StreamUtils.toList(delColumns, GenTableColumn::getColumnId);
genTableColumnMapper.deleteBatchIds(ids);
}
}
/**
*
*
* @param tableNames
* @return
*/
@Override
public byte[] downloadCode(String[] tableNames) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
for (String tableName : tableNames) {
generatorCode(tableName, zip);
}
IoUtil.close(zip);
return outputStream.toByteArray();
}
/**
*
*/
private void generatorCode(String tableName, ZipOutputStream zip) {
// 查询表信息
GenTable table = baseMapper.selectGenTableByName(tableName);
List<Long> menuIds = new ArrayList<>();
for (int i = 0; i < 6; i++) {
menuIds.add((Long) identifierGenerator.nextId(null));
}
table.setMenuIds(menuIds);
// 设置主键列信息
setPkColumn(table);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
try {
// 添加到zip
zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
IoUtil.write(zip, StandardCharsets.UTF_8, false, sw.toString());
IoUtil.close(sw);
zip.flush();
zip.closeEntry();
} catch (IOException e) {
log.error("渲染模板失败,表名:" + table.getTableName(), e);
}
}
}
/**
*
*
* @param genTable
*/
@Override
public void validateEdit(GenTable genTable) {
if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
String options = JsonUtils.toJsonString(genTable.getParams());
Dict paramsObj = JsonUtils.parseMap(options);
if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_CODE))) {
throw new BizException("树编码字段不能为空");
} else if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_PARENT_CODE))) {
throw new BizException("树父编码字段不能为空");
} else if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_NAME))) {
throw new BizException("树名称字段不能为空");
}
}
}
/**
*
*
* @param table
*/
public void setPkColumn(GenTable table) {
for (GenTableColumn column : table.getColumns()) {
if (column.isPk()) {
table.setPkColumn(column);
break;
}
}
if (ObjectUtil.isNull(table.getPkColumn())) {
table.setPkColumn(table.getColumns().get(0));
}
}
/**
*
*
* @param genTable
*/
public void setTableFromOptions(GenTable genTable) {
Dict paramsObj = JsonUtils.parseMap(genTable.getOptions());
if (ObjectUtil.isNotNull(paramsObj)) {
String treeCode = paramsObj.getStr(GenConstants.TREE_CODE);
String treeParentCode = paramsObj.getStr(GenConstants.TREE_PARENT_CODE);
String treeName = paramsObj.getStr(GenConstants.TREE_NAME);
String parentMenuId = paramsObj.getStr(GenConstants.PARENT_MENU_ID);
String parentMenuName = paramsObj.getStr(GenConstants.PARENT_MENU_NAME);
genTable.setTreeCode(treeCode);
genTable.setTreeParentCode(treeParentCode);
genTable.setTreeName(treeName);
genTable.setParentMenuId(parentMenuId);
genTable.setParentMenuName(parentMenuName);
}
}
/**
*
*
* @param table
* @param template
* @return
*/
public static String getGenPath(GenTable table, String template) {
String genPath = table.getGenPath();
if (StringUtils.equals(genPath, "/")) {
return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
}
return genPath + File.separator + VelocityUtils.getFileName(template, table);
}
}

View File

@ -0,0 +1,134 @@
package cc.iotkit.generator.service;
import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.generator.domain.GenTable;
import cc.iotkit.generator.domain.GenTableColumn;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
*
*
* @author Lion Li
*/
public interface IGenTableService {
/**
*
*
* @param tableId
* @return
*/
List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId);
/**
*
*
*
* @return
*/
Paging<GenTable> selectPageGenTableList(PageRequest<GenTable> pageQuery);
/**
*
*
* @return
*/
Paging<GenTable> selectPageDbTableList(PageRequest<GenTable> pageQuery);
/**
*
*
* @param tableNames
* @return
*/
List<GenTable> selectDbTableListByNames(Collection<String> tableNames);
/**
*
*
* @return
*/
List<GenTable> selectGenTableAll();
/**
*
*
* @param id ID
* @return
*/
GenTable selectGenTableById(Long id);
/**
*
*
* @param genTable
* @return
*/
void updateGenTable(GenTable genTable);
/**
*
*
* @param tableIds ID
* @return
*/
void deleteGenTableByIds(Collection<Long> tableIds);
/**
*
*
* @param tableList
*/
void importGenTable(List<GenTable> tableList);
/**
*
*
* @param tableId
* @return
*/
Map<String, String> previewCode(Long tableId);
/**
*
*
* @param tableName
* @return
*/
byte[] downloadCode(String tableName);
/**
*
*
* @param tableName
* @return
*/
void generatorCode(String tableName);
/**
*
*
* @param tableName
*/
void synchDb(String tableName);
/**
*
*
* @param tableNames
* @return
*/
byte[] downloadCode(String[] tableNames);
/**
*
*
* @param genTable
*/
void validateEdit(GenTable genTable);
}

View File

@ -0,0 +1,233 @@
package cc.iotkit.generator.util;
import cc.iotkit.common.satoken.utils.LoginHelper;
import cc.iotkit.common.utils.StringUtils;
import cc.iotkit.generator.config.GenConfig;
import cc.iotkit.generator.constant.GenConstants;
import cc.iotkit.generator.domain.GenTable;
import cc.iotkit.generator.domain.GenTableColumn;
import cn.hutool.core.util.ReUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.Arrays;
/**
*
*
* @author ruoyi
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class GenUtils {
/**
*
*/
public static void initTable(GenTable genTable, String operName) {
genTable.setClassName(convertClassName(genTable.getTableName()));
genTable.setPackageName(GenConfig.getPackageName());
genTable.setModuleName(getModuleName(GenConfig.getPackageName()));
genTable.setBusinessName(getBusinessName(genTable.getTableName()));
genTable.setFunctionName(replaceText(genTable.getTableComment()));
genTable.setFunctionAuthor(GenConfig.getAuthor());
genTable.setCreateBy(LoginHelper.getUserId());
}
/**
*
*/
public static void initColumnField(GenTableColumn column, GenTable table) {
String dataType = getDbType(column.getColumnType());
String columnName = column.getColumnName();
column.setTableId(table.getTableId());
column.setCreateBy(table.getCreateBy());
// 设置java字段名
column.setJavaField(StringUtils.toCamelCase(columnName));
// 设置默认类型
column.setJavaType(GenConstants.TYPE_STRING);
column.setQueryType(GenConstants.QUERY_EQ);
if (arraysContains(GenConstants.COLUMNTYPE_STR, dataType) || arraysContains(GenConstants.COLUMNTYPE_TEXT, dataType)) {
// 字符串长度超过500设置为文本域
Integer columnLength = getColumnLength(column.getColumnType());
String htmlType = columnLength >= 500 || arraysContains(GenConstants.COLUMNTYPE_TEXT, dataType) ? GenConstants.HTML_TEXTAREA : GenConstants.HTML_INPUT;
column.setHtmlType(htmlType);
} else if (arraysContains(GenConstants.COLUMNTYPE_TIME, dataType)) {
column.setJavaType(GenConstants.TYPE_DATE);
column.setHtmlType(GenConstants.HTML_DATETIME);
} else if (arraysContains(GenConstants.COLUMNTYPE_NUMBER, dataType)) {
column.setHtmlType(GenConstants.HTML_INPUT);
// 如果是浮点型 统一用BigDecimal
String[] str = StringUtils.split(StringUtils.substringBetween(column.getColumnType(), "(", ")"), StringUtils.SEPARATOR);
if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) {
column.setJavaType(GenConstants.TYPE_BIGDECIMAL);
}
// 如果是整形
else if (str != null && str.length == 1 && Integer.parseInt(str[0]) <= 10) {
column.setJavaType(GenConstants.TYPE_INTEGER);
}
// 长整形
else {
column.setJavaType(GenConstants.TYPE_LONG);
}
}
// BO对象 默认插入勾选
if (!arraysContains(GenConstants.COLUMNNAME_NOT_ADD, columnName) && !column.isPk()) {
column.setIsInsert(GenConstants.REQUIRE);
}
// BO对象 默认编辑勾选
if (!arraysContains(GenConstants.COLUMNNAME_NOT_EDIT, columnName)) {
column.setIsEdit(GenConstants.REQUIRE);
}
// BO对象 默认是否必填勾选
if (!arraysContains(GenConstants.COLUMNNAME_NOT_EDIT, columnName)) {
column.setIsRequired(GenConstants.REQUIRE);
}
// VO对象 默认返回勾选
if (!arraysContains(GenConstants.COLUMNNAME_NOT_LIST, columnName)) {
column.setIsList(GenConstants.REQUIRE);
}
// BO对象 默认查询勾选
if (!arraysContains(GenConstants.COLUMNNAME_NOT_QUERY, columnName) && !column.isPk()) {
column.setIsQuery(GenConstants.REQUIRE);
}
// 查询字段类型
if (StringUtils.endsWithIgnoreCase(columnName, "name")) {
column.setQueryType(GenConstants.QUERY_LIKE);
}
// 状态字段设置单选框
if (StringUtils.endsWithIgnoreCase(columnName, "status")) {
column.setHtmlType(GenConstants.HTML_RADIO);
}
// 类型&性别字段设置下拉框
else if (StringUtils.endsWithIgnoreCase(columnName, "type")
|| StringUtils.endsWithIgnoreCase(columnName, "sex")) {
column.setHtmlType(GenConstants.HTML_SELECT);
}
// 图片字段设置图片上传控件
else if (StringUtils.endsWithIgnoreCase(columnName, "image")) {
column.setHtmlType(GenConstants.HTML_IMAGE_UPLOAD);
}
// 文件字段设置文件上传控件
else if (StringUtils.endsWithIgnoreCase(columnName, "file")) {
column.setHtmlType(GenConstants.HTML_FILE_UPLOAD);
}
// 内容字段设置富文本控件
else if (StringUtils.endsWithIgnoreCase(columnName, "content")) {
column.setHtmlType(GenConstants.HTML_EDITOR);
}
}
/**
*
*
* @param arr
* @param targetValue
* @return
*/
public static boolean arraysContains(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
}
/**
*
*
* @param packageName
* @return
*/
public static String getModuleName(String packageName) {
int lastIndex = packageName.lastIndexOf(".");
int nameLength = packageName.length();
return StringUtils.substring(packageName, lastIndex + 1, nameLength);
}
/**
*
*
* @param tableName
* @return
*/
public static String getBusinessName(String tableName) {
int firstIndex = tableName.indexOf("_");
int nameLength = tableName.length();
String businessName = StringUtils.substring(tableName, firstIndex + 1, nameLength);
businessName = StringUtils.toCamelCase(businessName);
return businessName;
}
/**
* Java
*
* @param tableName
* @return
*/
public static String convertClassName(String tableName) {
boolean autoRemovePre = GenConfig.getAutoRemovePre();
String tablePrefix = GenConfig.getTablePrefix();
if (autoRemovePre && StringUtils.isNotEmpty(tablePrefix)) {
String[] searchList = StringUtils.split(tablePrefix, StringUtils.SEPARATOR);
tableName = replaceFirst(tableName, searchList);
}
return StringUtils.convertToCamelCase(tableName);
}
/**
*
*
* @param replacementm
* @param searchList
* @return
*/
public static String replaceFirst(String replacementm, String[] searchList) {
String text = replacementm;
for (String searchString : searchList) {
if (replacementm.startsWith(searchString)) {
text = replacementm.replaceFirst(searchString, "");
break;
}
}
return text;
}
/**
*
*
* @param text
* @return
*/
public static String replaceText(String text) {
return ReUtil.replaceAll(text, "(?:表|若依)", "");
}
/**
*
*
* @param columnType
* @return
*/
public static String getDbType(String columnType) {
if (StringUtils.indexOf(columnType, '(') > 0) {
return StringUtils.substringBefore(columnType, "(");
} else {
return columnType;
}
}
/**
*
*
* @param columnType
* @return
*/
public static Integer getColumnLength(String columnType) {
if (StringUtils.indexOf(columnType, '(') > 0) {
String length = StringUtils.substringBetween(columnType, "(", ")");
return Integer.valueOf(length);
} else {
return 0;
}
}
}

View File

@ -0,0 +1,35 @@
package cc.iotkit.generator.util;
import cc.iotkit.common.constant.Constants;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.velocity.app.Velocity;
import java.util.Properties;
/**
* VelocityEngine
*
* @author ruoyi
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class VelocityInitializer {
/**
* vm
*/
public static void initVelocity() {
Properties p = new Properties();
try {
// 加载classpath目录下的vm文件
p.setProperty("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
// 定义字符集
p.setProperty(Velocity.INPUT_ENCODING, Constants.UTF8);
// 初始化Velocity引擎指定配置Properties
Velocity.init(p);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,354 @@
package cc.iotkit.generator.util;
import cc.iotkit.common.utils.DateUtils;
import cc.iotkit.common.utils.JsonUtils;
import cc.iotkit.common.utils.StringUtils;
import cc.iotkit.generator.constant.GenConstants;
import cc.iotkit.generator.core.DataBaseHelper;
import cc.iotkit.generator.domain.GenTable;
import cc.iotkit.generator.domain.GenTableColumn;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Dict;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.velocity.VelocityContext;
import java.util.*;
/**
*
*
* @author ruoyi
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class VelocityUtils {
/**
*
*/
private static final String PROJECT_PATH = "main/java";
/**
* mybatis
*/
private static final String MYBATIS_PATH = "main/resources/mapper";
/**
*
*/
private static final String DEFAULT_PARENT_MENU_ID = "3";
/**
*
*
* @return
*/
public static VelocityContext prepareContext(GenTable genTable) {
String moduleName = genTable.getModuleName();
String businessName = genTable.getBusinessName();
String packageName = genTable.getPackageName();
String tplCategory = genTable.getTplCategory();
String functionName = genTable.getFunctionName();
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("tplCategory", genTable.getTplCategory());
velocityContext.put("tableName", genTable.getTableName());
velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】");
velocityContext.put("ClassName", genTable.getClassName());
velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName()));
velocityContext.put("moduleName", genTable.getModuleName());
velocityContext.put("BusinessName", StringUtils.capitalize(genTable.getBusinessName()));
velocityContext.put("businessName", genTable.getBusinessName());
velocityContext.put("basePackage", getPackagePrefix(packageName));
velocityContext.put("packageName", packageName);
velocityContext.put("author", genTable.getFunctionAuthor());
velocityContext.put("datetime", DateUtils.getDate());
velocityContext.put("pkColumn", genTable.getPkColumn());
velocityContext.put("importList", getImportList(genTable));
velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
velocityContext.put("columns", genTable.getColumns());
velocityContext.put("table", genTable);
velocityContext.put("dicts", getDicts(genTable));
setMenuVelocityContext(velocityContext, genTable);
if (GenConstants.TPL_TREE.equals(tplCategory)) {
setTreeVelocityContext(velocityContext, genTable);
}
return velocityContext;
}
public static void setMenuVelocityContext(VelocityContext context, GenTable genTable) {
String options = genTable.getOptions();
Dict paramsObj = JsonUtils.parseMap(options);
String parentMenuId = getParentMenuId(paramsObj);
context.put("parentMenuId", parentMenuId);
}
public static void setTreeVelocityContext(VelocityContext context, GenTable genTable) {
String options = genTable.getOptions();
Dict paramsObj = JsonUtils.parseMap(options);
String treeCode = getTreecode(paramsObj);
String treeParentCode = getTreeParentCode(paramsObj);
String treeName = getTreeName(paramsObj);
context.put("treeCode", treeCode);
context.put("treeParentCode", treeParentCode);
context.put("treeName", treeName);
context.put("expandColumn", getExpandColumn(genTable));
if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
context.put("tree_parent_code", paramsObj.get(GenConstants.TREE_PARENT_CODE));
}
if (paramsObj.containsKey(GenConstants.TREE_NAME)) {
context.put("tree_name", paramsObj.get(GenConstants.TREE_NAME));
}
}
/**
*
*
* @return
*/
public static List<String> getTemplateList(String tplCategory) {
List<String> templates = new ArrayList<String>();
templates.add("vm/java/model.java.vm");
templates.add("vm/java/vo.java.vm");
templates.add("vm/java/bo.java.vm");
// templates.add("vm/java/mapper.java.vm");
templates.add("vm/java/service.java.vm");
templates.add("vm/java/serviceImpl.java.vm");
templates.add("vm/java/controller.java.vm");
templates.add("vm/java/idata.java.vm");
templates.add("vm/java/idataimpl.java.vm");
templates.add("vm/java/tbmodel.java.vm");
templates.add("vm/java/repository.java.vm");
if (DataBaseHelper.isOracle()) {
templates.add("vm/sql/oracle/sql.vm");
} else if (DataBaseHelper.isPostgerSql()) {
templates.add("vm/sql/postgres/sql.vm");
} else if (DataBaseHelper.isSqlServer()) {
templates.add("vm/sql/sqlserver/sql.vm");
} else {
templates.add("vm/sql/sql.vm");
}
templates.add("vm/ts/api.ts.vm");
templates.add("vm/ts/types.ts.vm");
if (GenConstants.TPL_CRUD.equals(tplCategory)) {
templates.add("vm/vue/index.vue.vm");
} else if (GenConstants.TPL_TREE.equals(tplCategory)) {
templates.add("vm/vue/index-tree.vue.vm");
}
return templates;
}
/**
*
*/
public static String getFileName(String template, GenTable genTable) {
// 文件名称
String fileName = "";
// 包路径
String packageName = genTable.getPackageName();
// 模块名
String moduleName = genTable.getModuleName();
// 大写类名
String className = genTable.getClassName();
// 业务名称
String businessName = genTable.getBusinessName();
String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");
String mybatisPath = MYBATIS_PATH + "/" + moduleName;
String vuePath = "vue";
if (template.contains("domain.java.vm")) {
fileName = StringUtils.format("{}/domain/{}.java", javaPath, className);
}
if (template.endsWith("tbmodel.java.vm")) {
fileName = StringUtils.format("{}/data/model/Tb{}.java", javaPath, className);
} else if (template.endsWith("model.java.vm")) {
fileName = StringUtils.format("{}/model/{}.java", javaPath, className);
}
if (template.endsWith("repository.java.vm")) {
fileName = StringUtils.format("{}/repository/{}Repository.java", javaPath, className);
}
if (template.endsWith("idata.java.vm")) {
fileName = StringUtils.format("{}/data/I{}Data.java", javaPath, className);
} else if (template.endsWith("idataimpl.java.vm")) {
fileName = StringUtils.format("{}/data/impl/{}DataImpl.java", javaPath, className);
}
if (template.contains("vo.java.vm")) {
fileName = StringUtils.format("{}/dto/vo/{}Vo.java", javaPath, className);
}
if (template.contains("bo.java.vm")) {
fileName = StringUtils.format("{}/dto/bo/{}Bo.java", javaPath, className);
}
if (template.contains("mapper.java.vm")) {
fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className);
} else if (template.contains("service.java.vm")) {
fileName = StringUtils.format("{}/service/I{}Service.java", javaPath, className);
} else if (template.contains("serviceImpl.java.vm")) {
fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className);
} else if (template.contains("controller.java.vm")) {
fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className);
} else if (template.contains("mapper.xml.vm")) {
fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className);
} else if (template.contains("sql.vm")) {
fileName = businessName + "Menu.sql";
} else if (template.contains("api.ts.vm")) {
fileName = StringUtils.format("{}/api/{}/{}/index.ts", vuePath, moduleName, businessName);
} else if (template.contains("types.ts.vm")) {
fileName = StringUtils.format("{}/api/{}/{}/types.ts", vuePath, moduleName, businessName);
} else if (template.contains("index.vue.vm")) {
fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName);
} else if (template.contains("index-tree.vue.vm")) {
fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName);
}
return fileName;
}
/**
*
*
* @param packageName
* @return
*/
public static String getPackagePrefix(String packageName) {
int lastIndex = packageName.lastIndexOf(".");
return StringUtils.substring(packageName, 0, lastIndex);
}
/**
*
*
* @param genTable
* @return
*/
public static HashSet<String> getImportList(GenTable genTable) {
List<GenTableColumn> columns = genTable.getColumns();
HashSet<String> importList = new HashSet<>();
for (GenTableColumn column : columns) {
if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) {
importList.add("java.util.Date");
importList.add("com.fasterxml.jackson.annotation.JsonFormat");
} else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) {
importList.add("java.math.BigDecimal");
}
}
return importList;
}
/**
*
*
* @param genTable
* @return
*/
public static String getDicts(GenTable genTable) {
List<GenTableColumn> columns = genTable.getColumns();
Set<String> dicts = new HashSet<>();
addDicts(dicts, columns);
return StringUtils.join(dicts, ", ");
}
/**
*
*
* @param dicts
* @param columns
*/
public static void addDicts(Set<String> dicts, List<GenTableColumn> columns) {
for (GenTableColumn column : columns) {
if (!column.isSuperColumn() && StringUtils.isNotEmpty(column.getDictType()) && StringUtils.equalsAny(
column.getHtmlType(),
new String[] { GenConstants.HTML_SELECT, GenConstants.HTML_RADIO, GenConstants.HTML_CHECKBOX })) {
dicts.add("'" + column.getDictType() + "'");
}
}
}
/**
*
*
* @param moduleName
* @param businessName
* @return
*/
public static String getPermissionPrefix(String moduleName, String businessName) {
return StringUtils.format("{}:{}", moduleName, businessName);
}
/**
* ID
*
* @param paramsObj
* @return ID
*/
public static String getParentMenuId(Dict paramsObj) {
if (CollUtil.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID)
&& StringUtils.isNotEmpty(paramsObj.getStr(GenConstants.PARENT_MENU_ID))) {
return paramsObj.getStr(GenConstants.PARENT_MENU_ID);
}
return DEFAULT_PARENT_MENU_ID;
}
/**
*
*
* @param paramsObj
* @return
*/
public static String getTreecode(Map<String, Object> paramsObj) {
if (CollUtil.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.TREE_CODE)) {
return StringUtils.toCamelCase(Convert.toStr(paramsObj.get(GenConstants.TREE_CODE)));
}
return StringUtils.EMPTY;
}
/**
*
*
* @param paramsObj
* @return
*/
public static String getTreeParentCode(Dict paramsObj) {
if (CollUtil.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
return StringUtils.toCamelCase(paramsObj.getStr(GenConstants.TREE_PARENT_CODE));
}
return StringUtils.EMPTY;
}
/**
*
*
* @param paramsObj
* @return
*/
public static String getTreeName(Dict paramsObj) {
if (CollUtil.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.TREE_NAME)) {
return StringUtils.toCamelCase(paramsObj.getStr(GenConstants.TREE_NAME));
}
return StringUtils.EMPTY;
}
/**
*
*
* @param genTable
* @return
*/
public static int getExpandColumn(GenTable genTable) {
String options = genTable.getOptions();
Dict paramsObj = JsonUtils.parseMap(options);
String treeName = paramsObj.getStr(GenConstants.TREE_NAME);
int num = 0;
for (GenTableColumn column : genTable.getColumns()) {
if (column.isList()) {
num++;
String columnName = column.getColumnName();
if (columnName.equals(treeName)) {
break;
}
}
}
return num;
}
}

View File

@ -0,0 +1 @@
cc.iotkit.generator.config.MybatisPlusConfig

View File

@ -0,0 +1,45 @@
spring:
jpa:
show-sql: true
hibernate:
ddl-auto: update
properties:
hibernate:
format_sql: true
sql:
init:
# mysql 初始化
# schema-locations: classpath:sql/schema.sql
# postgrep 初始化
schema-locations: classpath:sql/schema-postgre.sql
mode: ALWAYS
datasource:
# 动态数据源文档 https://www.kancloud.cn/tracy5546/dynamic-datasource/content
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: true #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
# 主库数据源
master:
type: ${spring.datasource.type}
driverClassName: ${spring.datasource.driverClassName}
# jdbc 所有参数配置参考 https://lionli.blog.csdn.net/article/details/122018562
# rewriteBatchedStatements=true 批处理优化 大幅提升批量插入更新删除性能(对数据库有性能损耗 使用批量操作应考虑性能问题)
url: ${spring.datasource.url}
username: ${spring.datasource.url}
password: ${spring.datasource.password}
# 从库数据源
slave:
lazy: true
type: ${spring.datasource.type}
driverClassName: ${spring.datasource.driverClassName}
# jdbc 所有参数配置参考 https://lionli.blog.csdn.net/article/details/122018562
# rewriteBatchedStatements=true 批处理优化 大幅提升批量插入更新删除性能(对数据库有性能损耗 使用批量操作应考虑性能问题)
url: ${spring.datasource.url}
username: ${spring.datasource.username}
password: ${spring.datasource.password}

View File

@ -0,0 +1,33 @@
# 内置配置 不允许修改 如需修改请在 nacos 上写相同配置覆盖
# MyBatisPlus配置
# https://baomidou.com/config/
mybatis-plus:
# 启动时是否检查 MyBatis XML 文件的存在,默认不检查
checkConfigLocation: false
configuration:
# 自动驼峰命名规则camel case映射
mapUnderscoreToCamelCase: true
# MyBatis 自动映射策略
# NONE不启用 PARTIAL只对非嵌套 resultMap 自动映射 FULL对所有 resultMap 自动映射
autoMappingBehavior: FULL
# MyBatis 自动映射时未知列或未知属性处理策
# NONE不做处理 WARNING打印相关警告 FAILING抛出异常和详细信息
autoMappingUnknownColumnBehavior: NONE
# 更详细的日志输出 会有性能损耗 org.apache.ibatis.logging.stdout.StdOutImpl
# 关闭日志记录 (可单纯使用 p6spy 分析) org.apache.ibatis.logging.nologging.NoLoggingImpl
# 默认日志输出 org.apache.ibatis.logging.slf4j.Slf4jImpl
logImpl: org.apache.ibatis.logging.nologging.NoLoggingImpl
global-config:
# 是否打印 Logo banner
banner: true
dbConfig:
# 主键类型
# AUTO 自增 NONE 空 INPUT 用户输入 ASSIGN_ID 雪花 ASSIGN_UUID 唯一 UUID
idType: ASSIGN_ID
# 逻辑已删除值(框架表均使用此值 禁止随意修改)
logicDeleteValue: 2
# 逻辑未删除值
logicNotDeleteValue: 0
insertStrategy: NOT_NULL
updateStrategy: NOT_NULL
whereStrategy: NOT_NULL

View File

@ -0,0 +1,10 @@
# 代码生成
gen:
# 作者
author: iita
# 默认生成包路径 system 需改成自己的模块名称 如 system monitor tool
packageName: cc.iotkit.system
# 自动去除表前缀默认是false
autoRemovePre: false
# 表前缀(生成类名不会包含表前缀,多个用逗号分隔)
tablePrefix: sys_

View File

@ -0,0 +1,105 @@
<?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="cc.iotkit.generator.mapper.GenTableColumnMapper">
<resultMap type="cc.iotkit.generator.domain.GenTableColumn" id="GenTableColumnResult">
</resultMap>
<select id="selectDbTableColumnsByName" parameterType="String" resultMap="GenTableColumnResult">
<if test="@cc.iotkit.generator.core.DataBaseHelper@isMySql()">
select column_name,
(case when (is_nullable = 'no' <![CDATA[ && ]]> column_key != 'PRI') then '1' else null end) as is_required,
(case when column_key = 'PRI' then '1' else '0' end) as is_pk,
ordinal_position as sort,
column_comment,
(case when extra = 'auto_increment' then '1' else '0' end) as is_increment,
column_type
from information_schema.columns where table_schema = (select database()) and table_name = (#{tableName})
order by ordinal_position
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isH2()">
select column_name,
-- (case when (is_nullable = 'no' <![CDATA[ && ]]> column_key != 'PRI') then '1' else null end) as is_required,
(case when (is_nullable = 'no' ) then '1' else null end) as is_required,
-- (case when column_key = 'PRI' then '1' else '0' end) as is_pk,
ordinal_position as sort
-- column_comment,
-- (case when extra = 'auto_increment' then '1' else '0' end) as is_increment,
-- column_type
from information_schema.columns where table_name = (#{tableName})
order by ordinal_position
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isOracle()">
select lower(temp.column_name) as column_name,
(case when (temp.nullable = 'N' and temp.constraint_type != 'P') then '1' else null end) as is_required,
(case when temp.constraint_type = 'P' then '1' else '0' end) as is_pk,
temp.column_id as sort,
temp.comments as column_comment,
(case when temp.constraint_type = 'P' then '1' else '0' end) as is_increment,
lower(temp.data_type) as column_type
from (
select col.column_id, col.column_name,col.nullable, col.data_type, colc.comments, uc.constraint_type, row_number()
over (partition by col.column_name order by uc.constraint_type desc) as row_flg
from user_tab_columns col
left join user_col_comments colc on colc.table_name = col.table_name and colc.column_name = col.column_name
left join user_cons_columns ucc on ucc.table_name = col.table_name and ucc.column_name = col.column_name
left join user_constraints uc on uc.constraint_name = ucc.constraint_name
where col.table_name = upper(#{tableName})
) temp
WHERE temp.row_flg = 1
ORDER BY temp.column_id
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isPostgerSql()">
SELECT column_name, is_required, is_pk, sort, column_comment, is_increment, column_type
FROM (
SELECT c.relname AS table_name,
a.attname AS column_name,
d.description AS column_comment,
CASE WHEN a.attnotnull AND con.conname IS NULL THEN 1 ELSE 0
END AS is_required,
CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0
END AS is_pk,
a.attnum AS sort,
CASE WHEN "position"(pg_get_expr(ad.adbin, ad.adrelid),
((c.relname::text || '_'::text) || a.attname::text) || '_seq'::text) > 0 THEN 1 ELSE 0
END AS is_increment,
btrim(
CASE WHEN t.typelem <![CDATA[ <> ]]> 0::oid AND t.typlen = '-1'::integer THEN 'ARRAY'::text ELSE
CASE WHEN t.typtype = 'd'::"char" THEN format_type(t.typbasetype, NULL::integer)
ELSE format_type(a.atttypid, NULL::integer) END
END, '"'::text
) AS column_type
FROM pg_attribute a
JOIN (pg_class c JOIN pg_namespace n ON c.relnamespace = n.oid) ON a.attrelid = c.oid
LEFT JOIN pg_description d ON d.objoid = c.oid AND a.attnum = d.objsubid
LEFT JOIN pg_constraint con ON con.conrelid = c.oid AND (a.attnum = ANY (con.conkey))
LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
LEFT JOIN pg_type t ON a.atttypid = t.oid
WHERE (c.relkind = ANY (ARRAY ['r'::"char", 'p'::"char"]))
AND a.attnum > 0
AND n.nspname = 'public'::name
ORDER BY c.relname, a.attnum
) temp
WHERE table_name = (#{tableName})
AND column_type <![CDATA[ <> ]]> '-'
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isSqlServer()">
SELECT
cast(A.NAME as nvarchar) as column_name,
cast(B.NAME as nvarchar) + (case when B.NAME = 'numeric' then '(' + cast(A.prec as nvarchar) + ',' + cast(A.scale as nvarchar) + ')' else '' end) as column_type,
cast(G.[VALUE] as nvarchar) as column_comment,
(SELECT 1 FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE Z WHERE TABLE_NAME = D.NAME and A.NAME = Z.column_name ) as is_pk,
colorder as sort
FROM SYSCOLUMNS A
LEFT JOIN SYSTYPES B ON A.XTYPE = B.XUSERTYPE
INNER JOIN SYSOBJECTS D ON A.ID = D.ID AND D.XTYPE='U' AND D.NAME != 'DTPROPERTIES'
LEFT JOIN SYS.EXTENDED_PROPERTIES G ON A.ID = G.MAJOR_ID AND A.COLID = G.MINOR_ID
LEFT JOIN SYS.EXTENDED_PROPERTIES F ON D.ID = F.MAJOR_ID AND F.MINOR_ID = 0
WHERE D.NAME = #{tableName}
ORDER BY A.COLORDER
</if>
</select>
</mapper>

View File

@ -0,0 +1,309 @@
<?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="cc.iotkit.generator.mapper.GenTableMapper">
<!-- 多结构嵌套自动映射需带上每个实体的主键id 否则映射会失败 -->
<resultMap type="cc.iotkit.generator.domain.GenTable" id="GenTableResult">
<id property="tableId" column="table_id" />
<result property="tableName" column="table_name" />
<result property="tableComment" column="table_comment" />
<result property="subTableName" column="sub_table_name" />
<result property="subTableFkName" column="sub_table_fk_name" />
<result property="className" column="class_name" />
<result property="tplCategory" column="tpl_category" />
<result property="packageName" column="package_name" />
<result property="moduleName" column="module_name" />
<result property="businessName" column="business_name" />
<result property="functionName" column="function_name" />
<result property="functionAuthor" column="function_author" />
<result property="genType" column="gen_type" />
<result property="genPath" column="gen_path" />
<result property="options" column="options" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="remark" column="remark" />
<collection property="columns" javaType="java.util.List" resultMap="GenTableColumnResult" />
</resultMap>
<resultMap type="cc.iotkit.generator.domain.GenTableColumn" id="GenTableColumnResult">
<id property="columnId" column="column_id" />
<result property="tableId" column="table_id" />
<result property="columnName" column="column_name" />
<result property="columnComment" column="column_comment" />
<result property="columnType" column="column_type" />
<result property="javaType" column="java_type" />
<result property="javaField" column="java_field" />
<result property="isPk" column="is_pk" />
<result property="isIncrement" column="is_increment" />
<result property="isRequired" column="is_required" />
<result property="isInsert" column="is_insert" />
<result property="isEdit" column="is_edit" />
<result property="isList" column="is_list" />
<result property="isQuery" column="is_query" />
<result property="queryType" column="query_type" />
<result property="htmlType" column="html_type" />
<result property="dictType" column="dict_type" />
<result property="sort" column="sort" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
</resultMap>
<select id="selectPageDbTableList" resultMap="GenTableResult">
<if test="@cc.iotkit.generator.core.DataBaseHelper@isMySql()">
select table_name, table_comment, create_time, update_time
from information_schema.tables
where table_schema = (select database())
AND table_name NOT LIKE 'pj_%' AND table_name NOT LIKE 'gen_%'
<if test="genTable.params.genTableNames != null and genTable.params.genTableNames.size > 0">
AND table_name NOT IN
<foreach collection="genTable.params.genTableNames" open="(" close=")" separator="," item="item">
#{item}
</foreach>
</if>
<if test="genTable.tableName != null and genTable.tableName != ''">
AND lower(table_name) like lower(concat('%', #{genTable.tableName}, '%'))
</if>
<if test="genTable.tableComment != null and genTable.tableComment != ''">
AND lower(table_comment) like lower(concat('%', #{genTable.tableComment}, '%'))
</if>
order by create_time desc
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isH2()">
select table_name
from information_schema.tables
where
table_name NOT LIKE 'pj_%' AND table_name NOT LIKE 'gen_%'
<if test="genTable.params.genTableNames != null and genTable.params.genTableNames.size > 0">
AND table_name NOT IN
<foreach collection="genTable.params.genTableNames" open="(" close=")" separator="," item="item">
#{item}
</foreach>
</if>
<if test="genTable.tableName != null and genTable.tableName != ''">
AND lower(table_name) like lower(concat('%', #{genTable.tableName}, '%'))
</if>
<if test="genTable.tableComment != null and genTable.tableComment != ''">
AND lower(table_comment) like lower(concat('%', #{genTable.tableComment}, '%'))
</if>
order by table_name desc
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isOracle()">
select lower(dt.table_name) as table_name, dtc.comments as table_comment, uo.created as create_time, uo.last_ddl_time as update_time
from user_tables dt, user_tab_comments dtc, user_objects uo
where dt.table_name = dtc.table_name
and dt.table_name = uo.object_name
and uo.object_type = 'TABLE'
AND dt.table_name NOT LIKE 'pj_%' AND dt.table_name NOT LIKE 'GEN_%'
<if test="genTable.params.genTableNames != null and genTable.params.genTableNames.size > 0">
AND lower(dt.table_name) NOT IN
<foreach collection="genTable.params.genTableNames" open="(" close=")" separator="," item="item">
#{item}
</foreach>
</if>
<if test="genTable.tableName != null and genTable.tableName != ''">
AND lower(dt.table_name) like lower(concat(concat('%', #{genTable.tableName}), '%'))
</if>
<if test="genTable.tableComment != null and genTable.tableComment != ''">
AND lower(dtc.comments) like lower(concat(concat('%', #{genTable.tableComment}), '%'))
</if>
order by create_time desc
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isPostgerSql()">
select table_name, table_comment, create_time, update_time
from (
SELECT c.relname AS table_name,
obj_description(c.oid) AS table_comment,
CURRENT_TIMESTAMP AS create_time,
CURRENT_TIMESTAMP AS update_time
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE (c.relkind = ANY (ARRAY ['r'::"char", 'p'::"char"]))
AND c.relname != 'spatial_%'::text
AND n.nspname = 'public'::name
AND n.nspname <![CDATA[ <> ]]> ''::name
) list_table
where table_name NOT LIKE 'pj_%' AND table_name NOT LIKE 'gen_%'
<if test="genTable.params.genTableNames != null and genTable.params.genTableNames.size > 0">
AND table_name NOT IN
<foreach collection="genTable.params.genTableNames" open="(" close=")" separator="," item="item">
#{item}
</foreach>
</if>
<if test="genTable.tableName != null and genTable.tableName != ''">
AND lower(table_name) like lower(concat('%', #{genTable.tableName}, '%'))
</if>
<if test="genTable.tableComment != null and genTable.tableComment != ''">
AND lower(table_comment) like lower(concat('%', #{genTable.tableComment}, '%'))
</if>
order by create_time desc
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isSqlServer()">
SELECT cast(D.NAME as nvarchar) as table_name,
cast(F.VALUE as nvarchar) as table_comment,
crdate as create_time,
refdate as update_time
FROM SYSOBJECTS D
INNER JOIN SYS.EXTENDED_PROPERTIES F ON D.ID = F.MAJOR_ID
AND F.MINOR_ID = 0 AND D.XTYPE = 'U' AND D.NAME != 'DTPROPERTIES'
AND D.NAME NOT LIKE 'pj_%' AND D.NAME NOT LIKE 'gen_%'
<if test="genTable.params.genTableNames != null and genTable.params.genTableNames.size > 0">
AND D.NAME NOT IN
<foreach collection="genTable.params.genTableNames" open="(" close=")" separator="," item="item">
#{item}
</foreach>
</if>
<if test="genTable.tableName != null and genTable.tableName != ''">
AND lower(D.NAME) like lower(concat(N'%', N'${genTable.tableName}', N'%'))
</if>
<if test="genTable.tableComment != null and genTable.tableComment != ''">
AND lower(CAST(F.VALUE AS nvarchar)) like lower(concat(N'%', N'${genTable.tableComment}', N'%'))
</if>
order by crdate desc
</if>
</select>
<select id="selectDbTableListByNames" resultMap="GenTableResult">
<if test="@cc.iotkit.generator.core.DataBaseHelper@isMySql()">
select table_name, table_comment, create_time, update_time from information_schema.tables
where table_name NOT LIKE 'pj_%' and table_name NOT LIKE 'gen_%' and table_schema = (select database())
and table_name in
<foreach collection="list" item="name" open="(" separator="," close=")">
#{name}
</foreach>
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isH2()">
select table_name from information_schema.tables
where table_name NOT LIKE 'pj_%' and table_name NOT LIKE 'gen_%'
and table_name in
<foreach collection="list" item="name" open="(" separator="," close=")">
#{name}
</foreach>
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isOracle()">
select lower(dt.table_name) as table_name, dtc.comments as table_comment, uo.created as create_time, uo.last_ddl_time as update_time
from user_tables dt, user_tab_comments dtc, user_objects uo
where dt.table_name = dtc.table_name
and dt.table_name = uo.object_name
and uo.object_type = 'TABLE'
AND dt.table_name NOT LIKE 'pj_%' AND dt.table_name NOT LIKE 'GEN_%'
and lower(dt.table_name) in
<foreach collection="list" item="name" open="(" separator="," close=")">
#{name}
</foreach>
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isPostgerSql()">
select table_name, table_comment, create_time, update_time
from (
SELECT c.relname AS table_name,
obj_description(c.oid) AS table_comment,
CURRENT_TIMESTAMP AS create_time,
CURRENT_TIMESTAMP AS update_time
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE (c.relkind = ANY (ARRAY ['r'::"char", 'p'::"char"]))
AND c.relname != 'spatial_%'::text
AND n.nspname = 'public'::name
AND n.nspname <![CDATA[ <> ]]> ''::name
) list_table
where table_name NOT LIKE 'pj_%' and table_name NOT LIKE 'gen_%'
and table_name in
<foreach collection="list" item="name" open="(" separator="," close=")">
#{name}
</foreach>
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isSqlServer()">
SELECT cast(D.NAME as nvarchar) as table_name,
cast(F.VALUE as nvarchar) as table_comment,
crdate as create_time,
refdate as update_time
FROM SYSOBJECTS D
INNER JOIN SYS.EXTENDED_PROPERTIES F ON D.ID = F.MAJOR_ID
AND F.MINOR_ID = 0 AND D.XTYPE = 'U' AND D.NAME != 'DTPROPERTIES'
AND D.NAME NOT LIKE 'pj_%' AND D.NAME NOT LIKE 'gen_%'
AND D.NAME in
<foreach collection="list" item="name" open="(" separator="," close=")">
#{name}
</foreach>
</if>
</select>
<select id="selectTableByName" parameterType="String" resultMap="GenTableResult">
<if test="@cc.iotkit.generator.core.DataBaseHelper@isMySql()">
select table_name, table_comment, create_time, update_time from information_schema.tables
where table_name NOT LIKE 'pj_%' and table_name NOT LIKE 'gen_%' and table_schema = (select database())
and table_name = #{tableName}
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isOracle()">
select lower(dt.table_name) as table_name, dtc.comments as table_comment, uo.created as create_time, uo.last_ddl_time as update_time
from user_tables dt, user_tab_comments dtc, user_objects uo
where dt.table_name = dtc.table_name
and dt.table_name = uo.object_name
and uo.object_type = 'TABLE'
AND dt.table_name NOT LIKE 'pj_%' AND dt.table_name NOT LIKE 'GEN_%'
AND dt.table_name NOT IN (select table_name from gen_table)
and lower(dt.table_name) = #{tableName}
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isPostgerSql()">
select table_name, table_comment, create_time, update_time
from (
SELECT c.relname AS table_name,
obj_description(c.oid) AS table_comment,
CURRENT_TIMESTAMP AS create_time,
CURRENT_TIMESTAMP AS update_time
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE (c.relkind = ANY (ARRAY ['r'::"char", 'p'::"char"]))
AND c.relname != 'spatial_%'::text
AND n.nspname = 'public'::name
AND n.nspname <![CDATA[ <> ]]> ''::name
) list_table
where table_name NOT LIKE 'pj_%' and table_name NOT LIKE 'gen_%'
and table_name = #{tableName}
</if>
<if test="@cc.iotkit.generator.core.DataBaseHelper@isSqlServer()">
SELECT cast(D.NAME as nvarchar) as table_name,
cast(F.VALUE as nvarchar) as table_comment,
crdate as create_time,
refdate as update_time
FROM SYSOBJECTS D
INNER JOIN SYS.EXTENDED_PROPERTIES F ON D.ID = F.MAJOR_ID
AND F.MINOR_ID = 0 AND D.XTYPE = 'U' AND D.NAME != 'DTPROPERTIES'
AND D.NAME NOT LIKE 'pj_%' AND D.NAME NOT LIKE 'gen_%'
AND D.NAME = #{tableName}
</if>
</select>
<select id="selectGenTableById" parameterType="Long" resultMap="GenTableResult">
SELECT t.table_id, t.data_name, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id
where t.table_id = #{tableId} order by c.sort
</select>
<select id="selectGenTableByName" parameterType="String" resultMap="GenTableResult">
SELECT t.table_id, t.data_name, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark,
c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id
where t.table_name = #{tableName} order by c.sort
</select>
<select id="selectGenTableAll" parameterType="String" resultMap="GenTableResult">
SELECT t.table_id, t.data_name, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.options, t.remark,
c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort
FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id
order by c.sort
</select>
<select id="selectTableNameList" resultType="java.lang.String">
select table_name from gen_table where data_name = #{dataName,jdbcType=VARCHAR}
</select>
</mapper>

View File

@ -0,0 +1,3 @@
java包使用 `.` 分割 resource 目录使用 `/` 分割
<br>
此文件目的 防止文件夹粘连找不到 `xml` 文件

View File

@ -0,0 +1,52 @@
package ${packageName}.dto.bo;
import ${packageName}.model.${ClassName};
import cc.iotkit.common.api.BaseDto;
import cc.iotkit.common.validate.AddGroup;
import cc.iotkit.common.validate.EditGroup;
import io.github.linpeilie.annotations.AutoMapper;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import jakarta.validation.constraints.*;
#foreach ($import in $importList)
import ${import};
#end
/**
* ${functionName}业务对象 ${tableName}
*
* @author ${author}
* @date ${datetime}
*/
@Data
@EqualsAndHashCode(callSuper = true)
@AutoMapper(target = ${ClassName}.class, reverseConvertGenerate = false)
public class ${ClassName}Bo extends BaseDto {
#foreach ($column in $columns)
#if(!$table.isSuperColumn($column.javaField) && ($column.query || $column.insert || $column.edit))
/**
* $column.columnComment
*/
#if($column.insert && $column.edit)
#set($Group="AddGroup.class, EditGroup.class")
#elseif($column.insert)
#set($Group="AddGroup.class")
#elseif($column.edit)
#set($Group="EditGroup.class")
#end
#if($column.required)
#if($column.javaType == 'String')
@NotBlank(message = "$column.columnComment不能为空", groups = { $Group })
#else
@NotNull(message = "$column.columnComment不能为空", groups = { $Group })
#end
#end
@ApiModelProperty(value = "$column.columnComment", required = ${column.required})
private $column.javaType $column.javaField;
#end
#end
}

View File

@ -0,0 +1,113 @@
package ${packageName}.controller;
import java.util.List;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cc.iotkit.common.log.annotation.Log;
import cc.iotkit.common.web.core.BaseController;
import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.api.Request;
import cc.iotkit.common.validate.AddGroup;
import cc.iotkit.common.validate.EditGroup;
import cc.iotkit.common.log.enums.BusinessType;
import cc.iotkit.common.excel.utils.ExcelUtil;
import ${packageName}.dto.vo.${ClassName}Vo;
import ${packageName}.dto.bo.${ClassName}Bo;
import ${packageName}.service.I${ClassName}Service;
/**
* ${functionName}
*
* @author ${author}
* @date ${datetime}
*/
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/${moduleName}/${businessName}")
public class ${ClassName}Controller extends BaseController {
private final I${ClassName}Service ${className}Service;
/**
* 查询${functionName}列表
*/
@SaCheckPermission("${permissionPrefix}:list")
@PostMapping("/list")
@ApiOperation("查询${functionName}列表")
#if($table.crud || $table.sub)
public Paging<${ClassName}Vo> list( PageRequest<${ClassName}Bo> pageQuery) {
return ${className}Service.queryPageList(pageQuery);
}
#elseif($table.tree)
public List<${ClassName}Vo> list(@RequestBody Request<${ClassName}Bo> query) {
List<${ClassName}Vo> list = ${className}Service.queryList(query.getData());
return list;
}
#end
/**
* 导出${functionName}列表
*/
@ApiOperation("导出${functionName}列表")
@SaCheckPermission("${permissionPrefix}:export")
@Log(title = "${functionName}", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(${ClassName}Bo bo, HttpServletResponse response) {
List<${ClassName}Vo> list = ${className}Service.queryList(bo);
ExcelUtil.exportExcel(list, "${functionName}", ${ClassName}Vo.class, response);
}
/**
* 获取${functionName}详细信息
*
*/
@SaCheckPermission("${permissionPrefix}:query")
@PostMapping("/getDetail")
@ApiOperation("获取${functionName}详细信息")
public ${ClassName}Vo getDetail(@Validated @RequestBody Request<Long> request) {
return ${className}Service.queryById(request.getData());
}
/**
* 新增${functionName}
*/
@SaCheckPermission("${permissionPrefix}:add")
@Log(title = "${functionName}", businessType = BusinessType.INSERT)
@PostMapping(value = "/add")
@ApiOperation("新增${functionName}")
public Long add(@Validated(AddGroup.class) @RequestBody Request<${ClassName}Bo> request) {
return ${className}Service.insertByBo(request.getData());
}
/**
* 修改${functionName}
*/
@SaCheckPermission("${permissionPrefix}:edit")
@Log(title = "${functionName}", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
@ApiOperation("修改${functionName}")
public boolean edit(@Validated(EditGroup.class) @RequestBody Request<${ClassName}Bo> request) {
return ${className}Service.updateByBo(request.getData());
}
/**
* 删除${functionName}
*
*/
@SaCheckPermission("${permissionPrefix}:remove")
@Log(title = "${functionName}", businessType = BusinessType.DELETE)
@PostMapping("/delete")
@ApiOperation("删除${functionName}")
public boolean remove(@Validated @RequestBody Request<List<Long>> query) {
return ${className}Service.deleteWithValidByIds(query.getData(), true);
}
}

View File

@ -0,0 +1,16 @@
package ${packageName}.data;
import cc.iotkit.data.ICommonData;
import ${packageName}.model.${ClassName};
import java.util.List;
/**
* 数据接口
*
* @author ${author}
* @date ${datetime}
*/
public interface I${ClassName}Data extends ICommonData<${ClassName}, Long> {
}

View File

@ -0,0 +1,135 @@
package ${packageName}.data;
import ${packageName}.repository.${ClassName}Repository;
import ${packageName}.data.I${ClassName}Data;
import ${packageName}.data.model.Tb${ClassName};
import ${packageName}.model.${ClassName};
import java.util.List;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import cc.iotkit.data.util.PredicateBuilder;
import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.utils.StringUtils;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import com.google.common.collect.Lists;
import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.data.util.PageBuilder;
import static ${packageName}.data.model.QTb${ClassName}.tb${ClassName};
/**
* 数据实现接口
*
* @author ${author}
* @date ${datetime}
*/
@Primary
@Service
@RequiredArgsConstructor
public class ${ClassName}DataImpl implements I${ClassName}Data {
private final ${ClassName}Repository baseRepository;
private final JPAQueryFactory jpaQueryFactory;
@Override
public Paging<${ClassName}> findAll(PageRequest<${ClassName}> pageRequest) {
return PageBuilder.toPaging(baseRepository.findAll(buildQueryCondition(pageRequest.getData()), PageBuilder.toPageable(pageRequest))).to(${ClassName}.class);
}
private Predicate buildQueryCondition(${ClassName} bo) {
PredicateBuilder builder = PredicateBuilder.instance();
if(Objects.nonNull(bo)) {
#foreach($column in $columns)
#if($column.query)
#set($queryType=$column.queryType)
#set($javaField=$column.javaField)
#set($javaType=$column.javaType)
#set($columnName=$column.columnName)
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
#if($queryType != 'BETWEEN')
#if($javaType == 'String')
#set($condition='StringUtils.isNotBlank(bo.get'+$AttrName+'())')
#else
#set($condition='bo.get'+$AttrName+'() != null')
#end
builder.and($condition, () -> tb${ClassName}.${javaField}.eq(bo.get${AttrName}()));
#else
builder.and(params.get("begin$AttrName") != null && params.get("end$AttrName") != null,
() -> tb${ClassName}.${javaField}.bettwen(params.get("begin$AttrName"), params.get("end$AttrName")));
#end
#end
#end
}
return builder.build();
}
@Override
public List<${ClassName}> findByIds(Collection<Long> ids) {
List<Tb${ClassName}> allById = baseRepository.findAllById(ids);
return MapstructUtils.convert(allById, ${ClassName}.class);
}
@Override
public ${ClassName} save(${ClassName} data) {
Object o = baseRepository.save(MapstructUtils.convert(data, Tb${ClassName}.class));
return MapstructUtils.convert(o, ${ClassName}.class);
}
@Override
public void batchSave(List<${ClassName}> data) {
baseRepository.saveAll(MapstructUtils.convert(data, Tb${ClassName}.class));
}
@Override
public void deleteById(Long id) {
baseRepository.deleteById(id);
}
@Override
public void deleteByIds(Collection<Long> ids) {
baseRepository.deleteAllById(ids);
}
@Override
public ${ClassName} findById(Long id) {
Tb${ClassName} ret = jpaQueryFactory.select(tb${ClassName}).from(tb${ClassName}).where(tb${ClassName}.id.eq(id)).fetchOne();
return MapstructUtils.convert(ret, ${ClassName}.class);
}
@Override
public long count() {
return baseRepository.count();
}
@Override
public List<IotContributor> findAll() {
return MapstructUtils.convert(baseRepository.findAll(), IotContributor.class);
}
@Override
public List<IotContributor> findAllByCondition(IotContributor data) {
Iterable<TbIotContributor> all = baseRepository.findAll(buildQueryCondition(data));
return MapstructUtils.convert(Lists.newArrayList(all), IotContributor.class);
}
@Override
public IotContributor findOneByCondition(IotContributor data) {
Optional<TbIotContributor> one = baseRepository.findOne(buildQueryCondition(data));
if(one.isPresent()){
return MapstructUtils.convert(one.get(), IotContributor.class);
}
return null;
}
}

View File

@ -0,0 +1,15 @@
package ${packageName}.mapper;
import ${packageName}.domain.${ClassName};
import ${packageName}.domain.vo.${ClassName}Vo;
import cc.iotkit.common.mybatis.core.mapper.BaseMapperPlus;
/**
* ${functionName}Mapper接口
*
* @author ${author}
* @date ${datetime}
*/
public interface ${ClassName}Mapper extends BaseMapperPlus<${ClassName}, ${ClassName}Vo> {
}

View File

@ -0,0 +1,50 @@
package ${packageName}.model;
import cc.iotkit.model.Id;
#foreach ($column in $columns)
#if($column.javaField=='tenantId')
#set($IsTenant=1)
#end
#end
#if($IsTenant==1)
import cc.iotkit.model.TenantModel;
#else
import cc.iotkit.model.BaseModel;
#end
import lombok.Data;
import lombok.EqualsAndHashCode;
#foreach ($import in $importList)
import ${import};
#end
import java.io.Serializable;
/**
* ${functionName}对象 ${tableName}
*
* @author ${author}
* @date ${datetime}
*/
#if($IsTenant==1)
#set($Entity="TenantModel")
#else
#set($Entity="BaseModel")
#end
@Data
@EqualsAndHashCode(callSuper = true)
public class ${ClassName} extends ${Entity} implements Id<Long>, Serializable{
private static final long serialVersionUID = 1L;
#foreach ($column in $columns)
#if(!$table.isSuperColumn($column.javaField))
/**
* $column.columnComment
*/
private $column.javaType $column.javaField;
#end
#end
}

View File

@ -0,0 +1,15 @@
package ${packageName}.data.dao;
import ${packageName}.data.model.Tb${ClassName};
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
/**
* ${functionName}对象 ${tableName}
*
* @author ${author}
* @date ${datetime}
*/
public interface ${ClassName}Repository extends JpaRepository<Tb${ClassName}, Long>, QuerydslPredicateExecutor<Tb${ClassName}> {
}

View File

@ -0,0 +1,53 @@
package ${packageName}.service;
import ${packageName}.dto.vo.${ClassName}Vo;
import ${packageName}.dto.bo.${ClassName}Bo;
#if($table.crud || $table.sub)
#end
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.api.PageRequest;
import java.util.Collection;
import java.util.List;
/**
* ${functionName}Service接口
*
* @author ${author}
* @date ${datetime}
*/
public interface I${ClassName}Service {
/**
* 查询${functionName}
*/
${ClassName}Vo queryById(${pkColumn.javaType} ${pkColumn.javaField});
#if($table.crud || $table.sub)
/**
* 查询${functionName}列表
*/
Paging<${ClassName}Vo> queryPageList(PageRequest<${ClassName}Bo> pageQuery);
#end
/**
* 查询${functionName}列表
*/
List<${ClassName}Vo> queryList(${ClassName}Bo bo);
/**
* 新增${functionName}
*/
Long insertByBo(${ClassName}Bo bo);
/**
* 修改${functionName}
*/
Boolean updateByBo(${ClassName}Bo bo);
/**
* 校验并批量删除${functionName}信息
*/
Boolean deleteWithValidByIds(Collection<${pkColumn.javaType}> ids, Boolean isValid);
}

View File

@ -0,0 +1,109 @@
package ${packageName}.service.impl;
import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.common.utils.StringUtils;
#if($table.crud || $table.sub)
import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
#end
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import ${packageName}.dto.bo.${ClassName}Bo;
import ${packageName}.dto.vo.${ClassName}Vo;
import ${packageName}.model.${ClassName};
import ${packageName}.service.I${ClassName}Service;
import ${packageName}.data.I${ClassName}Data;
import java.util.List;
import java.util.Collection;
import cc.iotkit.common.exception.BizException;
/**
* ${functionName}Service业务层处理
*
* @author ${author}
* @date ${datetime}
*/
@RequiredArgsConstructor
@Service
public class ${ClassName}ServiceImpl implements I${ClassName}Service {
private final I${ClassName}Data baseData;
/**
* 查询${functionName}
*/
@Override
public ${ClassName}Vo queryById(${pkColumn.javaType} ${pkColumn.javaField}){
return MapstructUtils.convert(baseData.findById(${pkColumn.javaField}), ${ClassName}Vo.class);
}
#if($table.crud || $table.sub)
/**
* 查询${functionName}列表
*/
@Override
public Paging<${ClassName}Vo> queryPageList(PageRequest<${ClassName}Bo> pageQuery) {
Paging<${ClassName}Vo> result = baseData.findAll(pageQuery.to(${ClassName}.class)).to(${ClassName}Vo.class);
return result;
}
#end
/**
* 查询${functionName}列表
*/
@Override
public List<${ClassName}Vo> queryList(${ClassName}Bo bo) {
return MapstructUtils.convert(baseData.findAllByCondition(bo.to(${ClassName}.class)), ${ClassName}Vo.class);
}
/**
* 新增${functionName}
*/
@Override
public Long insertByBo(${ClassName}Bo bo) {
${ClassName} add = MapstructUtils.convert(bo, ${ClassName}.class);
validEntityBeforeSave(add);
baseData.save(add);
if (add == null) {
throw new BizException("新增失败");
}
#set($pk=$pkColumn.javaField.substring(0,1).toUpperCase() + ${pkColumn.javaField.substring(1)})
return add.get$pk();
}
/**
* 修改${functionName}
*/
@Override
public Boolean updateByBo(${ClassName}Bo bo) {
${ClassName} update = MapstructUtils.convert(bo, ${ClassName}.class);
validEntityBeforeSave(update);
${ClassName} ret = baseData.save(update);
if(ret == null){
return false;
}
return true;
}
/**
* 保存前的数据校验
*/
private void validEntityBeforeSave(${ClassName} entity){
//TODO 做一些数据校验,如唯一约束
}
/**
* 批量删除${functionName}
*/
@Override
public Boolean deleteWithValidByIds(Collection<${pkColumn.javaType}> ids, Boolean isValid) {
if(isValid){
//TODO 做一些业务上的校验,判断是否需要校验
}
baseData.deleteByIds(ids);
return true;
}
}

View File

@ -0,0 +1,71 @@
package ${packageName}.data.model;
import ${packageName}.model.IotContributor;
import io.github.linpeilie.annotations.AutoMapper;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#foreach ($column in $columns)
#if($column.javaField=='tenantId')
#set($IsTenant=1)
#end
#end
#if($IsTenant==1)
import cc.iotkit.model.TenantModel;
#else
import cc.iotkit.data.model.BaseEntity;
#end
import lombok.Data;
import lombok.EqualsAndHashCode;
#foreach ($import in $importList)
import ${import};
#end
import javax.persistence.Table;
import javax.persistence.Entity;
/**
* ${functionName}对象 ${tableName}
*
* @author ${author}
* @date ${datetime}
*/
#if($IsTenant==1)
#set($Entity="TenantEntity")
#else
#set($Entity="BaseEntity")
#end
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "${tableName}")
@AutoMapper(target = ${ClassName}.class)
public class Tb${ClassName} extends ${Entity} {
#foreach ($column in $columns)
#if(!$table.isSuperColumn($column.javaField))
/**
* $column.columnComment
*/
#if($column.javaField=='delFlag')
#end
#if($column.javaField=='version')
#end
#if($column.isPk==1)
@Id
@GeneratedValue(generator = "SnowflakeIdGenerator")
@GenericGenerator(name = "SnowflakeIdGenerator", strategy = "cc.iotkit.data.config.id.SnowflakeIdGenerator")
#end
@ApiModelProperty(value = "$column.columnComment")
private $column.javaType $column.javaField;
#end
#end
}

View File

@ -0,0 +1,61 @@
package ${packageName}.dto.vo;
#foreach ($import in $importList)
import ${import};
#end
import ${packageName}.model.${ClassName};
import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
import com.alibaba.excel.annotation.ExcelProperty;
import cc.iotkit.common.excel.annotation.ExcelDictFormat;
import cc.iotkit.common.excel.convert.ExcelDictConvert;
import io.github.linpeilie.annotations.AutoMapper;
import lombok.Data;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
/**
* ${functionName}视图对象 ${tableName}
*
* @author ${author}
* @date ${datetime}
*/
@Data
@ExcelIgnoreUnannotated
@AutoMapper(target = ${ClassName}.class)
public class ${ClassName}Vo implements Serializable {
private static final long serialVersionUID = 1L;
#foreach ($column in $columns)
#if($column.list)
/**
* $column.columnComment
*/
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#if(${column.dictType} && ${column.dictType} != '')
@ExcelProperty(value = "${comment}", converter = ExcelDictConvert.class)
@ExcelDictFormat(dictType = "${column.dictType}")
#elseif($parentheseIndex != -1)
@ExcelProperty(value = "${comment}", converter = ExcelDictConvert.class)
@ExcelDictFormat(readConverterExp = "$column.readConverterExp()")
#else
@ExcelProperty(value = "${comment}")
#end
@ApiModelProperty(value = "${comment}")
private $column.javaType $column.javaField;
#end
#end
}

View File

@ -0,0 +1,47 @@
import request from '@/utils/request'
import { ${BusinessName}Form, ${BusinessName}Query, ${BusinessName}VO } from './types'
// 查询${functionName}列表
export function list${BusinessName}(query: ${BusinessName}Query): AxiosPromise<${BusinessName}VO[]> {
return request({
url: '/${moduleName}/${businessName}/list',
method: 'post',
params: query
})
}
// 查询${functionName}详细
export function get${BusinessName}(${pkColumn.javaField}: string | number) : AxiosPromise<${BusinessName}VO> {
return request({
url: '/${moduleName}/${businessName}/getDetail',
method: 'post',
data: ${pkColumn.javaField}
})
}
// 新增${functionName}
export function add${BusinessName}(data: ${BusinessName}Form) {
return request({
url: '/${moduleName}/${businessName}/add',
method: 'post',
data,
})
}
// 修改${functionName}
export function update${BusinessName}(data: ${BusinessName}Form) {
return request({
url: '/${moduleName}/${businessName}/edit',
method: 'post',
data,
})
}
// 删除${functionName}
export function del${BusinessName}(${pkColumn.javaField}: Array<string | number>) {
return request({
url: '/${moduleName}/${businessName}/' + ${pkColumn.javaField},
method: 'post',
data: ${pkColumn.javaField}
})
}

View File

@ -0,0 +1,19 @@
-- 菜单 SQL
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[0]}, '${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 103, 1, sysdate, null, null, '${functionName}菜单');
-- 按钮 SQL
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[1]}, '${functionName}查询', ${table.menuIds[0]}, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 103, 1, sysdate, null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[2]}, '${functionName}新增', ${table.menuIds[0]}, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 103, 1, sysdate, null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[3]}, '${functionName}修改', ${table.menuIds[0]}, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 103, 1, sysdate, null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[4]}, '${functionName}删除', ${table.menuIds[0]}, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 103, 1, sysdate, null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[5]}, '${functionName}导出', ${table.menuIds[0]}, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 103, 1, sysdate, null, null, '');

View File

@ -0,0 +1,20 @@
-- 菜单 SQL
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[0]}, '${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 103, 1, now(), null, null, '${functionName}菜单');
-- 按钮 SQL
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[1]}, '${functionName}查询', ${table.menuIds[0]}, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 103, 1, now(), null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[2]}, '${functionName}新增', ${table.menuIds[0]}, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 103, 1, now(), null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[3]}, '${functionName}修改', ${table.menuIds[0]}, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 103, 1, now(), null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[4]}, '${functionName}删除', ${table.menuIds[0]}, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 103, 1, now(), null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[5]}, '${functionName}导出', ${table.menuIds[0]}, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 103, 1, now(), null, null, '');

View File

@ -0,0 +1,19 @@
-- 菜单 SQL
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[0]}, '${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 103, 1, sysdate(), null, null, '${functionName}菜单');
-- 按钮 SQL
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[1]}, '${functionName}查询', ${table.menuIds[0]}, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 103, 1, sysdate(), null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[2]}, '${functionName}新增', ${table.menuIds[0]}, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 103, 1, sysdate(), null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[3]}, '${functionName}修改', ${table.menuIds[0]}, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 103, 1, sysdate(), null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[4]}, '${functionName}删除', ${table.menuIds[0]}, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 103, 1, sysdate(), null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[5]}, '${functionName}导出', ${table.menuIds[0]}, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 103, 1, sysdate(), null, null, '');

View File

@ -0,0 +1,19 @@
-- 菜单 SQL
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[0]}, '${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 103, 1, getdate(), null, null, '${functionName}菜单');
-- 按钮 SQL
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[1]}, '${functionName}查询', ${table.menuIds[0]}, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 103, 1, getdate(), null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[2]}, '${functionName}新增', ${table.menuIds[0]}, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 103, 1, getdate(), null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[3]}, '${functionName}修改', ${table.menuIds[0]}, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 103, 1, getdate(), null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[4]}, '${functionName}删除', ${table.menuIds[0]}, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 103, 1, getdate(), null, null, '');
insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark)
values(${table.menuIds[5]}, '${functionName}导出', ${table.menuIds[0]}, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 103, 1, getdate(), null, null, '');

View File

@ -0,0 +1,48 @@
import request from '@/utils/request';
import {AxiosPromise} from 'axios';
import {${BusinessName}Form, ${BusinessName}Query, ${BusinessName}VO} from './types';
// 查询${functionName}列表
export const list${BusinessName}(query: ${BusinessName}Query): AxiosPromise<${BusinessName}VO[]> {
return request({
url: '/${moduleName}/${businessName}/list',
method: 'post',
params: query
})
}
// 查询${functionName}详细
export const get${BusinessName}(${pkColumn.javaField}: string | number): AxiosPromise<${BusinessName}VO> {
return request({
url: '/${moduleName}/${businessName}/getDetail',
method: 'post',
data: ${pkColumn.javaField}
})
}
// 新增${functionName}
export const add${BusinessName}(data: ${BusinessName}Form) {
return request({
url: '/${moduleName}/${businessName}/add',
method: 'post',
data
})
}
// 修改${functionName}
export const update${BusinessName}(data: ${BusinessName}Form) {
return request({
url: '/${moduleName}/${businessName}/edit',
method: 'post',
data: data
})
}
// 删除${functionName}
export const del${BusinessName}(${pkColumn.javaField}: Array<string | number>) {
return request({
url: '/${moduleName}/${businessName}/' + ${pkColumn.javaField},
method: 'post',
data: ${pkColumn.javaField}
})
}

View File

@ -0,0 +1,44 @@
export interface ${BusinessName}VO {
#foreach ($column in $columns)
#if($column.insert || $column.edit)
/**
* $column.columnComment
*/
$column.javaField:#if($column.javaField.indexOf("id") != -1 || $column.javaField.indexOf("Id") != -1) string | number;
#elseif($column.javaType == 'Long' || $column.javaType == 'Integer' || $column.javaType == 'Double' || $column.javaType == 'Float' || $column.javaType == 'BigDecimal') number;
#elseif($column.javaType == 'Boolean') boolean;
#else string;
#end
#end
#end
}
export interface ${BusinessName}Form extends BaseEntity {
#foreach ($column in $columns)
#if($column.insert || $column.edit)
/**
* $column.columnComment
*/
$column.javaField?:#if($column.javaField.indexOf("id") != -1 || $column.javaField.indexOf("Id") != -1) string | number;
#elseif($column.javaType == 'Long' || $column.javaType == 'Integer' || $column.javaType == 'Double' || $column.javaType == 'Float' || $column.javaType == 'BigDecimal') number;
#elseif($column.javaType == 'Boolean') boolean;
#else string;
#end
#end
#end
}
export interface ${BusinessName}Query #if(!${treeCode})extends PageQuery #end{
#foreach ($column in $columns)
#if($column.query)
/**
* $column.columnComment
*/
$column.javaField?:#if($column.javaField.indexOf("id") != -1 || $column.javaField.indexOf("Id") != -1) string | number;
#elseif($column.javaType == 'Long' || $column.javaType == 'Integer' || $column.javaType == 'Double' || $column.javaType == 'Float' || $column.javaType == 'BigDecimal') number;
#elseif($column.javaType == 'Boolean') boolean;
#else string;
#end
#end
#end
}

View File

@ -0,0 +1,501 @@
<template>
<div class="p-2">
<transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
<div class="search" v-show="showSearch">
<el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
#foreach($column in $columns)
#if($column.query)
#set($dictType=$column.dictType)
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#if($column.htmlType == "input" || $column.htmlType == "textarea")
<el-form-item label="${comment}" prop="${column.javaField}">
<el-input v-model="queryParams.${column.javaField}" placeholder="请输入${comment}" clearable @keyup.enter="handleQuery" />
</el-form-item>
#elseif(($column.htmlType == "select" || $column.htmlType == "radio") && "" != $dictType)
<el-form-item label="${comment}" prop="${column.javaField}">
<el-select v-model="queryParams.${column.javaField}" placeholder="请选择${comment}" clearable>
<el-option
v-for="dict in ${dictType}"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
#elseif(($column.htmlType == "select" || $column.htmlType == "radio") && $dictType)
<el-form-item label="${comment}" prop="${column.javaField}">
<el-select v-model="queryParams.${column.javaField}" placeholder="请选择${comment}" clearable>
<el-option label="请选择字典生成" value="" />
</el-select>
</el-form-item>
#elseif($column.htmlType == "datetime" && $column.queryType != "BETWEEN")
<el-form-item label="${comment}" prop="${column.javaField}">
<el-date-picker clearable
v-model="queryParams.${column.javaField}"
type="date"
value-format="YYYY-MM-DD"
placeholder="选择${comment}"
/>
</el-form-item>
#elseif($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
<el-form-item label="${comment}" style="width: 308px">
<el-date-picker
v-model="daterange${AttrName}"
value-format="YYYY-MM-DD HH:mm:ss"
type="daterange"
range-separator="-"
start-placeholder="开始日期"
end-placeholder="结束日期"
:default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
/>
</el-form-item>
#end
#end
#end
<el-form-item>
<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
<el-button icon="Refresh" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
</div>
</transition>
<el-card shadow="never">
<template #header>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['${moduleName}:${businessName}:add']">新增</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
</el-col>
<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
</el-row>
</template>
<el-table
v-loading="loading"
:data="${businessName}List"
row-key="${treeCode}"
:default-expand-all="isExpandAll"
:tree-props="{children: 'children', hasChildren: 'hasChildren'}"
ref="${businessName}TableRef"
>
#foreach($column in $columns)
#set($javaField=$column.javaField)
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#if($column.pk)
#elseif($column.list && $column.htmlType == "datetime")
<el-table-column label="${comment}" align="center" prop="${javaField}" width="180">
<template #default="scope">
<span>{{ parseTime(scope.row.${javaField}, '{y}-{m}-{d}') }}</span>
</template>
</el-table-column>
#elseif($column.list && $column.htmlType == "imageUpload")
<el-table-column label="${comment}" align="center" prop="${javaField}" width="100">
<template #default="scope">
<image-preview :src="scope.row.${javaField}" :width="50" :height="50"/>
</template>
</el-table-column>
#elseif($column.list && $column.dictType && "" != $column.dictType)
<el-table-column label="${comment}" align="center" prop="${javaField}">
<template #default="scope">
#if($column.htmlType == "checkbox")
<dict-tag :options="${column.dictType}" :value="scope.row.${javaField} ? scope.row.${javaField}.split(',') : []"/>
#else
<dict-tag :options="${column.dictType}" :value="scope.row.${javaField}"/>
#end
</template>
</el-table-column>
#elseif($column.list && "" != $javaField)
#if(${foreach.index} == 1)
<el-table-column label="${comment}" prop="${javaField}" />
#else
<el-table-column label="${comment}" align="center" prop="${javaField}" />
#end
#end
#end
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template #default="scope">
<el-tooltip content="修改" placement="top">
<el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['${moduleName}:${businessName}:edit']" />
</el-tooltip>
<el-tooltip content="新增" placement="top">
<el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['${moduleName}:${businessName}:add']" />
</el-tooltip>
<el-tooltip content="删除" placement="top">
<el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['${moduleName}:${businessName}:remove']" />
</el-tooltip>
</template>
</el-table-column>
</el-table>
</el-card>
<!-- 添加或修改${functionName}对话框 -->
<el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
<el-form ref="${businessName}FormRef" :model="form" :rules="rules" label-width="80px">
#foreach($column in $columns)
#set($field=$column.javaField)
#if($column.insert && !$column.pk)
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#set($dictType=$column.dictType)
#if("" != $treeParentCode && $column.javaField == $treeParentCode)
<el-form-item label="${comment}" prop="${treeParentCode}">
<el-tree-select
v-model="form.${treeParentCode}"
:data="${businessName}Options"
:props="{ value: '${treeCode}', label: '${treeName}', children: 'children' }"
value-key="${treeCode}"
placeholder="请选择${comment}"
check-strictly
/>
</el-form-item>
#elseif($column.htmlType == "input")
<el-form-item label="${comment}" prop="${field}">
<el-input v-model="form.${field}" placeholder="请输入${comment}" />
</el-form-item>
#elseif($column.htmlType == "imageUpload")
<el-form-item label="${comment}" prop="${field}">
<image-upload v-model="form.${field}"/>
</el-form-item>
#elseif($column.htmlType == "fileUpload")
<el-form-item label="${comment}" prop="${field}">
<file-upload v-model="form.${field}"/>
</el-form-item>
#elseif($column.htmlType == "editor")
<el-form-item label="${comment}">
<editor v-model="form.${field}" :min-height="192"/>
</el-form-item>
#elseif($column.htmlType == "select" && "" != $dictType)
<el-form-item label="${comment}" prop="${field}">
<el-select v-model="form.${field}" placeholder="请选择${comment}">
<el-option
v-for="dict in ${dictType}"
:key="dict.value"
:label="dict.label"
#if($column.javaType == "Integer" || $column.javaType == "Long")
:value="parseInt(dict.value)"
#else
:value="dict.value"
#end
></el-option>
</el-select>
</el-form-item>
#elseif($column.htmlType == "select" && $dictType)
<el-form-item label="${comment}" prop="${field}">
<el-select v-model="form.${field}" placeholder="请选择${comment}">
<el-option label="请选择字典生成" value="" />
</el-select>
</el-form-item>
#elseif($column.htmlType == "checkbox" && "" != $dictType)
<el-form-item label="${comment}" prop="${field}">
<el-checkbox-group v-model="form.${field}">
<el-checkbox
v-for="dict in ${dictType}"
:key="dict.value"
:label="dict.value">
{{dict.label}}
</el-checkbox>
</el-checkbox-group>
</el-form-item>
#elseif($column.htmlType == "checkbox" && $dictType)
<el-form-item label="${comment}" prop="${field}">
<el-checkbox-group v-model="form.${field}">
<el-checkbox>请选择字典生成</el-checkbox>
</el-checkbox-group>
</el-form-item>
#elseif($column.htmlType == "radio" && "" != $dictType)
<el-form-item label="${comment}" prop="${field}">
<el-radio-group v-model="form.${field}">
<el-radio
v-for="dict in ${dictType}"
:key="dict.value"
#if($column.javaType == "Integer" || $column.javaType == "Long")
:label="parseInt(dict.value)"
#else
:label="dict.value"
#end
>{{dict.label}}</el-radio>
</el-radio-group>
</el-form-item>
#elseif($column.htmlType == "radio" && $dictType)
<el-form-item label="${comment}" prop="${field}">
<el-radio-group v-model="form.${field}">
<el-radio label="1">请选择字典生成</el-radio>
</el-radio-group>
</el-form-item>
#elseif($column.htmlType == "datetime")
<el-form-item label="${comment}" prop="${field}">
<el-date-picker clearable
v-model="form.${field}"
type="datetime"
value-format="YYYY-MM-DD HH:mm:ss"
placeholder="选择${comment}"
/>
</el-form-item>
#elseif($column.htmlType == "textarea")
<el-form-item label="${comment}" prop="${field}">
<el-input v-model="form.${field}" type="textarea" placeholder="请输入内容" />
</el-form-item>
#end
#end
#end
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup name="${BusinessName}" lang="ts">
import {add${BusinessName}, ${BusinessName}Form, get${BusinessName}, list${BusinessName}, ${BusinessName}Query, update${BusinessName}, ${BusinessName}VO} from "@/api/";
import {ComponentInternalInstance} from 'vue';
import {ElForm, ElTable} from 'element-plus';
type ${BusinessName}Option = {
${treeCode}: number;
${treeName}: string;
children?: ${BusinessName}Option[];
}
const { proxy } = getCurrentInstance() as ComponentInternalInstance;;
#if(${dicts} != '')
#set($dictsNoSymbol=$dicts.replace("'", ""))
const { ${dictsNoSymbol} } = toRefs<any>(proxy?.useDict(${dicts}));
#end
const ${businessName}List = ref<${BusinessName}VO[]>([]);
const ${businessName}Options = ref<${BusinessName}Option[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);
const queryFormRef = ref(ElForm);
const ${businessName}FormRef = ref(ElForm);
const ${businessName}TableRef = ref(ElTable)
const dialog = reactive<DialogOption>({
visible: false,
title: ''
});
#foreach ($column in $columns)
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
const daterange${AttrName} = ref([]);
#end
#end
const initFormData: ${BusinessName}Form = {
#foreach ($column in $columns)
#if($column.insert || $column.edit)
#if($column.htmlType == "checkbox")
$column.javaField: []#if($foreach.count != $columns.size()),#end
#else
$column.javaField: undefined#if($foreach.count != $columns.size()),#end
#end
#end
#end
}
const data = reactive<PageData<${BusinessName}Form, ${BusinessName}Query>>({
form: {...initFormData},
queryParams: {
#foreach ($column in $columns)
#if($column.query)
$column.javaField: undefined#if($foreach.count != $columns.size()),#end
#end
#end
},
rules: {
#foreach ($column in $columns)
#if($column.insert || $column.edit)
#if($column.required)
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
$column.javaField: [
{ required: true, message: "$comment不能为空", trigger: #if($column.htmlType == "select" || $column.htmlType == "radio")"change"#else"blur"#end }
]#if($foreach.count != $columns.size()),#end
#end
#end
#end
}
});
const { queryParams, form, rules } = toRefs(data);
/** 查询${functionName}列表 */
const getList = async () => {
loading.value = true;
#foreach ($column in $columns)
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
queryParams.value.params = {};
#break
#end
#end
#foreach ($column in $columns)
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
if (null != daterange${AttrName} && '' != daterange${AttrName}) {
queryParams.value.params["begin${AttrName}"] = daterange${AttrName}.value[0];
queryParams.value.params["end${AttrName}"] = daterange${AttrName}.value[1];
}
#end
#end
const res = await list${BusinessName}(queryParams.value);
const data = proxy?.handleTree<${BusinessName}VO>(res.data, "${treeCode}", "${treeParentCode}");
if (data) {
${businessName}List.value = data;
loading.value = false;
}
}
/** 查询${functionName}下拉树结构 */
const getTreeselect = async () => {
const res = await list${BusinessName}();
${businessName}Options.value = [];
const data: ${BusinessName}Option = { ${treeCode}: 0, ${treeName}: '顶级节点', children: [] };
data.children = proxy?.handleTree<${BusinessName}Option>(res.data, "${treeCode}", "${treeParentCode}");
${businessName}Options.value.push(data);
}
// 取消按钮
const cancel = () => {
reset();
dialog.visible = false;
}
// 表单重置
const reset = () => {
form.value = {...initFormData}
${businessName}FormRef.value.resetFields();
}
/** 搜索按钮操作 */
const handleQuery = () => {
getList();
}
/** 重置按钮操作 */
const resetQuery = () => {
#foreach ($column in $columns)
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
daterange${AttrName}.value = [];
#end
#end
queryFormRef.value.resetFields();
handleQuery();
}
/** 新增按钮操作 */
const handleAdd = (row?: ${BusinessName}VO) => {
dialog.visible = true;
dialog.title = "添加${functionName}";
nextTick(() => {
reset();
getTreeselect();
if (row != null && row.${treeCode}) {
form.value.${treeParentCode} = row.${treeCode};
} else {
form.value.${treeParentCode} = 0;
}
});
}
/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
isExpandAll.value = !isExpandAll.value;
toggleExpandAll(${businessName}List.value, isExpandAll.value)
}
/** 展开/折叠操作 */
const toggleExpandAll = (data: ${BusinessName}VO[], status: boolean) => {
data.forEach((item) => {
${businessName}TableRef.value.toggleRowExpansion(item, status)
if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
})
}
/** 修改按钮操作 */
const handleUpdate = (row: ${BusinessName}VO) => {
loading.value = true;
dialog.visible = true;
dialog.title = "修改${functionName}";
nextTick(async () => {
reset();
await getTreeselect();
if (row != null) {
form.value.${treeParentCode} = row.${treeCode};
}
const res = await get${BusinessName}(row.${treeCode});
loading.value = false;
Object.assign(form.value, res.data);
#foreach ($column in $columns)
#if($column.htmlType == "checkbox")
form.value.$column.javaField = form.value.${column.javaField}.split(",");
#end
#end
});
}
/** 提交按钮 */
const submitForm = () => {
${businessName}FormRef.value.validate((valid: boolean) => {
if (valid) {
buttonLoading.value = true;
#foreach ($column in $columns)
#if($column.htmlType == "checkbox")
form.value.$column.javaField = form.value.${column.javaField}.join(",");
#end
#end
if (form.value.${pkColumn.javaField}) {
update${BusinessName}(form.value).finally(() => buttonLoading.value = false);
} else {
add${BusinessName}(form.value).finally(() => buttonLoading.value = false);
}
proxy?.#[[$modal]]#.msgSuccess("操作成功");
dialog.visible = false;
getList();
}
});
}
/** 删除按钮操作 */
const handleDelete = async (row: ${BusinessName}VO) => {
await proxy?.#[[$modal]]#.confirm('是否确认删除${functionName}编号为"' + row.${pkColumn.javaField} + '"的数据项?');
loading.value = true;
await del${BusinessName}(row.${pkColumn.javaField}).finally(() => loading.value = false);
await getList();
proxy?.#[[$modal]]#.msgSuccess("删除成功");
}
onMounted(() => {
getList();
});
</script>

View File

@ -0,0 +1,467 @@
<template>
<div class="p-2">
<transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
<div class="search" v-show="showSearch">
<el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
#foreach($column in $columns)
#if($column.query)
#set($dictType=$column.dictType)
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#if($column.htmlType == "input" || $column.htmlType == "textarea")
<el-form-item label="${comment}" prop="${column.javaField}">
<el-input v-model="queryParams.${column.javaField}" placeholder="请输入${comment}" clearable @keyup.enter="handleQuery" />
</el-form-item>
#elseif(($column.htmlType == "select" || $column.htmlType == "radio") && "" != $dictType)
<el-form-item label="${comment}" prop="${column.javaField}">
<el-select v-model="queryParams.${column.javaField}" placeholder="请选择${comment}" clearable>
<el-option
v-for="dict in ${dictType}"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
#elseif(($column.htmlType == "select" || $column.htmlType == "radio") && $dictType)
<el-form-item label="${comment}" prop="${column.javaField}">
<el-select v-model="queryParams.${column.javaField}" placeholder="请选择${comment}" clearable>
<el-option label="请选择字典生成" value="" />
</el-select>
</el-form-item>
#elseif($column.htmlType == "datetime" && $column.queryType != "BETWEEN")
<el-form-item label="${comment}" prop="${column.javaField}">
<el-date-picker clearable
v-model="queryParams.${column.javaField}"
type="date"
value-format="YYYY-MM-DD"
placeholder="请选择${comment}"
/>
</el-form-item>
#elseif($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
<el-form-item label="${comment}" style="width: 308px">
<el-date-picker
v-model="daterange${AttrName}"
value-format="YYYY-MM-DD HH:mm:ss"
type="daterange"
range-separator="-"
start-placeholder="开始日期"
end-placeholder="结束日期"
:default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
/>
</el-form-item>
#end
#end
#end
<el-form-item>
<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
<el-button icon="Refresh" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
</div>
</transition>
<el-card shadow="never">
<template #header>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['${moduleName}:${businessName}:add']">新增</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['${moduleName}:${businessName}:edit']">修改</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['${moduleName}:${businessName}:remove']">删除</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['${moduleName}:${businessName}:export']">导出</el-button>
</el-col>
<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
</el-row>
</template>
<el-table v-loading="loading" :data="${businessName}List" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center" />
#foreach($column in $columns)
#set($javaField=$column.javaField)
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#if($column.pk)
<el-table-column label="${comment}" align="center" prop="${javaField}" v-if="${column.list}" />
#elseif($column.list && $column.htmlType == "datetime")
<el-table-column label="${comment}" align="center" prop="${javaField}" width="180">
<template #default="scope">
<span>{{ parseTime(scope.row.${javaField}, '{y}-{m}-{d}') }}</span>
</template>
</el-table-column>
#elseif($column.list && $column.htmlType == "imageUpload")
<el-table-column label="${comment}" align="center" prop="${javaField}" width="100">
<template #default="scope">
<image-preview :src="scope.row.${javaField}" :width="50" :height="50"/>
</template>
</el-table-column>
#elseif($column.list && $column.dictType && "" != $column.dictType)
<el-table-column label="${comment}" align="center" prop="${javaField}">
<template #default="scope">
#if($column.htmlType == "checkbox")
<dict-tag :options="${column.dictType}" :value="scope.row.${javaField} ? scope.row.${javaField}.split(',') : []"/>
#else
<dict-tag :options="${column.dictType}" :value="scope.row.${javaField}"/>
#end
</template>
</el-table-column>
#elseif($column.list && "" != $javaField)
<el-table-column label="${comment}" align="center" prop="${javaField}" />
#end
#end
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template #default="scope">
<el-tooltip content="修改" placement="top">
<el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['${moduleName}:${businessName}:edit']"></el-button>
</el-tooltip>
<el-tooltip content="删除" placement="top">
<el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['${moduleName}:${businessName}:remove']"></el-button>
</el-tooltip>
</template>
</el-table-column>
</el-table>
<pagination
v-show="total>0"
:total="total"
v-model:page="queryParams.pageNum"
v-model:limit="queryParams.pageSize"
@pagination="getList"
/>
</el-card>
<!-- 添加或修改${functionName}对话框 -->
<el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
<el-form ref="${businessName}FormRef" :model="form" :rules="rules" label-width="80px">
#foreach($column in $columns)
#set($field=$column.javaField)
#if($column.insert && !$column.pk)
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
#set($dictType=$column.dictType)
#if($column.htmlType == "input")
<el-form-item label="${comment}" prop="${field}">
<el-input v-model="form.${field}" placeholder="请输入${comment}" />
</el-form-item>
#elseif($column.htmlType == "imageUpload")
<el-form-item label="${comment}" prop="${field}">
<image-upload v-model="form.${field}"/>
</el-form-item>
#elseif($column.htmlType == "fileUpload")
<el-form-item label="${comment}" prop="${field}">
<file-upload v-model="form.${field}"/>
</el-form-item>
#elseif($column.htmlType == "editor")
<el-form-item label="${comment}">
<editor v-model="form.${field}" :min-height="192"/>
</el-form-item>
#elseif($column.htmlType == "select" && "" != $dictType)
<el-form-item label="${comment}" prop="${field}">
<el-select v-model="form.${field}" placeholder="请选择${comment}">
<el-option
v-for="dict in ${dictType}"
:key="dict.value"
:label="dict.label"
#if($column.javaType == "Integer" || $column.javaType == "Long")
:value="parseInt(dict.value)"
#else
:value="dict.value"
#end
></el-option>
</el-select>
</el-form-item>
#elseif($column.htmlType == "select" && $dictType)
<el-form-item label="${comment}" prop="${field}">
<el-select v-model="form.${field}" placeholder="请选择${comment}">
<el-option label="请选择字典生成" value="" />
</el-select>
</el-form-item>
#elseif($column.htmlType == "checkbox" && "" != $dictType)
<el-form-item label="${comment}" prop="${field}">
<el-checkbox-group v-model="form.${field}">
<el-checkbox
v-for="dict in ${dictType}"
:key="dict.value"
:label="dict.value">
{{dict.label}}
</el-checkbox>
</el-checkbox-group>
</el-form-item>
#elseif($column.htmlType == "checkbox" && $dictType)
<el-form-item label="${comment}" prop="${field}">
<el-checkbox-group v-model="form.${field}">
<el-checkbox>请选择字典生成</el-checkbox>
</el-checkbox-group>
</el-form-item>
#elseif($column.htmlType == "radio" && "" != $dictType)
<el-form-item label="${comment}" prop="${field}">
<el-radio-group v-model="form.${field}">
<el-radio
v-for="dict in ${dictType}"
:key="dict.value"
#if($column.javaType == "Integer" || $column.javaType == "Long")
:label="parseInt(dict.value)"
#else
:label="dict.value"
#end
>{{dict.label}}</el-radio>
</el-radio-group>
</el-form-item>
#elseif($column.htmlType == "radio" && $dictType)
<el-form-item label="${comment}" prop="${field}">
<el-radio-group v-model="form.${field}">
<el-radio label="1">请选择字典生成</el-radio>
</el-radio-group>
</el-form-item>
#elseif($column.htmlType == "datetime")
<el-form-item label="${comment}" prop="${field}">
<el-date-picker clearable
v-model="form.${field}"
type="datetime"
value-format="YYYY-MM-DD HH:mm:ss"
placeholder="请选择${comment}">
</el-date-picker>
</el-form-item>
#elseif($column.htmlType == "textarea")
<el-form-item label="${comment}" prop="${field}">
<el-input v-model="form.${field}" type="textarea" placeholder="请输入内容" />
</el-form-item>
#end
#end
#end
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup name="${BusinessName}" lang="ts">
import {add${BusinessName}, ${BusinessName}Form, get${BusinessName}, list${BusinessName}, ${BusinessName}Query, update${BusinessName}, ${BusinessName}VO} from '@/api/';
import {ComponentInternalInstance} from 'vue';
import {ElForm} from 'element-plus';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
#if(${dicts} != '')
#set($dictsNoSymbol=$dicts.replace("'", ""))
const { ${dictsNoSymbol} } = toRefs<any>(proxy?.useDict(${dicts}));
#end
const ${businessName}List = ref<${BusinessName}VO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
#foreach ($column in $columns)
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
const daterange${AttrName} = ref([]);
#end
#end
const queryFormRef = ref(ElForm);
const ${businessName}FormRef = ref(ElForm);
const dialog = reactive<DialogOption>({
visible: false,
title: ''
});
const initFormData: ${BusinessName}Form = {
#foreach ($column in $columns)
#if($column.insert || $column.edit)
#if($column.htmlType == "checkbox")
$column.javaField: []#if($foreach.count != $columns.size()),#end
#else
$column.javaField: undefined#if($foreach.count != $columns.size()),#end
#end
#end
#end
}
const data = reactive<PageData<${BusinessName}Form, ${BusinessName}Query>>({
form: {...initFormData},
queryParams: {
pageNum: 1,
pageSize: 10,
#foreach ($column in $columns)
#if($column.query)
$column.javaField: undefined#if($foreach.count != $columns.size()),#end
#end
#end
},
rules: {
#foreach ($column in $columns)
#if($column.insert || $column.edit)
#if($column.required)
#set($parentheseIndex=$column.columnComment.indexOf(""))
#if($parentheseIndex != -1)
#set($comment=$column.columnComment.substring(0, $parentheseIndex))
#else
#set($comment=$column.columnComment)
#end
$column.javaField: [
{ required: true, message: "$comment不能为空", trigger: #if($column.htmlType == "select" || $column.htmlType == "radio")"change"#else"blur"#end }
]#if($foreach.count != $columns.size()),#end
#end
#end
#end
}
});
const { queryParams, form, rules } = toRefs(data);
/** 查询${functionName}列表 */
const getList = async () => {
loading.value = true;
#foreach ($column in $columns)
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
queryParams.value.params = {};
#break
#end
#end
#foreach ($column in $columns)
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
if (null != daterange${AttrName} && '' != daterange${AttrName}) {
queryParams.value.params["begin${AttrName}"] = daterange${AttrName}.value[0];
queryParams.value.params["end${AttrName}"] = daterange${AttrName}.value[1];
}
#end
#end
const res = await list${BusinessName}(queryParams.value);
${businessName}List.value = res.rows;
total.value = res.total;
loading.value = false;
}
/** 取消按钮 */
const cancel = () => {
reset();
dialog.visible = false;
}
/** 表单重置 */
const reset = () => {
form.value = {...initFormData};
${businessName}FormRef.value.resetFields();
}
/** 搜索按钮操作 */
const handleQuery = () => {
queryParams.value.pageNum = 1;
getList();
}
/** 重置按钮操作 */
const resetQuery = () => {
#foreach ($column in $columns)
#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN")
#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)})
daterange${AttrName}.value = [];
#end
#end
queryFormRef.value.resetFields();
handleQuery();
}
/** 多选框选中数据 */
const handleSelectionChange = (selection: ${BusinessName}VO[]) => {
ids.value = selection.map(item => item.${pkColumn.javaField});
single.value = selection.length != 1;
multiple.value = !selection.length;
}
/** 新增按钮操作 */
const handleAdd = () => {
dialog.visible = true;
dialog.title = "添加${functionName}";
nextTick(() => {
reset();
});
}
/** 修改按钮操作 */
const handleUpdate = (row?: ${BusinessName}VO) => {
loading.value = true
dialog.visible = true;
dialog.title = "修改${functionName}";
nextTick(async () => {
reset();
const _${pkColumn.javaField} = row?.${pkColumn.javaField} || ids.value[0]
const res = await get${BusinessName}(_${pkColumn.javaField});
loading.value = false;
Object.assign(form.value, res.data);
#foreach ($column in $columns)
#if($column.htmlType == "checkbox")
form.value.$column.javaField = form.value.${column.javaField}.split(",");
#end
#end
});
}
/** 提交按钮 */
const submitForm = () => {
${businessName}FormRef.value.validate(async (valid: boolean) => {
if (valid) {
buttonLoading.value = true;
#foreach ($column in $columns)
#if($column.htmlType == "checkbox")
form.value.$column.javaField = form.value.${column.javaField}.join(",");
#end
#end
if (form.value.${pkColumn.javaField}) {
await update${BusinessName}(form.value).finally(() => buttonLoading.value = false);
} else {
await add${BusinessName}(form.value).finally(() => buttonLoading.value = false);
}
proxy?.#[[$modal]]#.msgSuccess("修改成功");
dialog.visible = false;
await getList();
}
});
}
/** 删除按钮操作 */
const handleDelete = async (row?: ${BusinessName}VO) => {
const _${pkColumn.javaField}s = row?.${pkColumn.javaField} || ids.value;
await proxy?.#[[$modal]]#.confirm('是否确认删除${functionName}编号为"' + _${pkColumn.javaField}s + '"的数据项?').finally(() => loading.value = false);
await del${BusinessName}(_${pkColumn.javaField}s);
proxy?.#[[$modal]]#.msgSuccess("删除成功");
await getList();
}
/** 导出按钮操作 */
const handleExport = () => {
proxy?.download('${moduleName}/${businessName}/export', {
...queryParams.value
}, `${businessName}_#[[${new Date().getTime()}]]#.xlsx`)
}
onMounted(() => {
getList();
});
</script>

View File

@ -0,0 +1,7 @@
<?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="${packageName}.mapper.${ClassName}Mapper">
</mapper>

View File

@ -20,6 +20,7 @@
<module>iot-plugin</module>
<module>iot-manager</module>
<module>iot-modbus</module>
<module>iot-generator</module>
</modules>
</project>

View File

@ -1,5 +1,6 @@
spring:
profiles:
# active: dev,generator # 使用application-dev.yml和代码生成器模块application-generator.yml配置
active: dev # 使用application-dev.yml 配置
# active: prd # 使用application-prd.yml 配置
# active: test # 使用application-test.yml 配置

View File

@ -0,0 +1,112 @@
-- ----------------------------
-- 18、代码生成业务表
-- ----------------------------
drop table if exists gen_table;
create table if not exists gen_table
(
table_id int8,
data_name varchar(200) default ''::varchar,
table_name varchar(200) default ''::varchar,
table_comment varchar(500) default ''::varchar,
sub_table_name varchar(64) default ''::varchar,
sub_table_fk_name varchar(64) default ''::varchar,
class_name varchar(100) default ''::varchar,
tpl_category varchar(200) default 'crud'::varchar,
package_name varchar(100) default null::varchar,
module_name varchar(30) default null::varchar,
business_name varchar(30) default null::varchar,
function_name varchar(50) default null::varchar,
function_author varchar(50) default null::varchar,
gen_type char default '0'::bpchar not null,
gen_path varchar(200) default '/'::varchar,
options varchar(1000) default null::varchar,
create_dept int8,
create_by int8,
create_time timestamp,
update_by int8,
update_time timestamp,
remark varchar(500) default null::varchar,
constraint gen_table_pk primary key (table_id)
);
comment on table gen_table is '代码生成业务表';
comment on column gen_table.table_id is '编号';
comment on column gen_table.data_name is '数据源名称';
comment on column gen_table.table_name is '表名称';
comment on column gen_table.table_comment is '表描述';
comment on column gen_table.sub_table_name is '关联子表的表名';
comment on column gen_table.sub_table_fk_name is '子表关联的外键名';
comment on column gen_table.class_name is '实体类名称';
comment on column gen_table.tpl_category is '使用的模板CRUD单表操作 TREE树表操作';
comment on column gen_table.package_name is '生成包路径';
comment on column gen_table.module_name is '生成模块名';
comment on column gen_table.business_name is '生成业务名';
comment on column gen_table.function_name is '生成功能名';
comment on column gen_table.function_author is '生成功能作者';
comment on column gen_table.gen_type is '生成代码方式0zip压缩包 1自定义路径';
comment on column gen_table.gen_path is '生成路径(不填默认项目路径)';
comment on column gen_table.options is '其它生成选项';
comment on column gen_table.create_dept is '创建部门';
comment on column gen_table.create_by is '创建者';
comment on column gen_table.create_time is '创建时间';
comment on column gen_table.update_by is '更新者';
comment on column gen_table.update_time is '更新时间';
comment on column gen_table.remark is '备注';
-- ----------------------------
-- 19、代码生成业务表字段
-- ----------------------------
drop table if exists gen_table_column;
create table if not exists gen_table_column
(
column_id int8,
table_id int8,
column_name varchar(200) default null::varchar,
column_comment varchar(500) default null::varchar,
column_type varchar(100) default null::varchar,
java_type varchar(500) default null::varchar,
java_field varchar(200) default null::varchar,
is_pk char default null::bpchar,
is_increment char default null::bpchar,
is_required char default null::bpchar,
is_insert char default null::bpchar,
is_edit char default null::bpchar,
is_list char default null::bpchar,
is_query char default null::bpchar,
query_type varchar(200) default 'EQ'::varchar,
html_type varchar(200) default null::varchar,
dict_type varchar(200) default ''::varchar,
sort int4,
create_dept int8,
create_by int8,
create_time timestamp,
update_by int8,
update_time timestamp,
constraint gen_table_column_pk primary key (column_id)
);
comment on table gen_table_column is '代码生成业务表字段';
comment on column gen_table_column.column_id is '编号';
comment on column gen_table_column.table_id is '归属表编号';
comment on column gen_table_column.column_name is '列名称';
comment on column gen_table_column.column_comment is '列描述';
comment on column gen_table_column.column_type is '列类型';
comment on column gen_table_column.java_type is 'JAVA类型';
comment on column gen_table_column.java_field is 'JAVA字段名';
comment on column gen_table_column.is_pk is '是否主键1是';
comment on column gen_table_column.is_increment is '是否自增1是';
comment on column gen_table_column.is_required is '是否必填1是';
comment on column gen_table_column.is_insert is '是否为插入字段1是';
comment on column gen_table_column.is_edit is '是否编辑字段1是';
comment on column gen_table_column.is_list is '是否列表字段1是';
comment on column gen_table_column.is_query is '是否查询字段1是';
comment on column gen_table_column.query_type is '查询方式(等于、不等于、大于、小于、范围)';
comment on column gen_table_column.html_type is '显示类型(文本框、文本域、下拉框、复选框、单选框、日期控件)';
comment on column gen_table_column.dict_type is '字典类型';
comment on column gen_table_column.sort is '排序';
comment on column gen_table_column.create_dept is '创建部门';
comment on column gen_table_column.create_by is '创建者';
comment on column gen_table_column.create_time is '创建时间';
comment on column gen_table_column.update_by is '更新者';
comment on column gen_table_column.update_time is '更新时间';

View File

@ -0,0 +1,60 @@
-- ----------------------------
-- 18、代码生成业务表
-- ----------------------------
create table if not exists gen_table (
table_id bigint(20) not null comment '编号',
data_name varchar(200) default '' comment '数据源名称',
table_name varchar(200) default '' comment '表名称',
table_comment varchar(500) default '' comment '表描述',
sub_table_name varchar(64) default null comment '关联子表的表名',
sub_table_fk_name varchar(64) default null comment '子表关联的外键名',
class_name varchar(100) default '' comment '实体类名称',
tpl_category varchar(200) default 'crud' comment '使用的模板crud单表操作 tree树表操作',
package_name varchar(100) comment '生成包路径',
module_name varchar(30) comment '生成模块名',
business_name varchar(30) comment '生成业务名',
function_name varchar(50) comment '生成功能名',
function_author varchar(50) comment '生成功能作者',
gen_type char(1) default '0' comment '生成代码方式0zip压缩包 1自定义路径',
gen_path varchar(200) default '/' comment '生成路径(不填默认项目路径)',
options varchar(1000) comment '其它生成选项',
create_dept bigint(20) default null comment '创建部门',
create_by bigint(20) default null comment '创建者',
create_time datetime comment '创建时间',
update_by bigint(20) default null comment '更新者',
update_time datetime comment '更新时间',
remark varchar(500) default null comment '备注',
primary key (table_id)
) engine=innodb comment = '代码生成业务表';
-- ----------------------------
-- 19、代码生成业务表字段
-- ----------------------------
create table if not exists gen_table_column (
column_id bigint(20) not null comment '编号',
table_id bigint(20) comment '归属表编号',
column_name varchar(200) comment '列名称',
column_comment varchar(500) comment '列描述',
column_type varchar(100) comment '列类型',
java_type varchar(500) comment 'JAVA类型',
java_field varchar(200) comment 'JAVA字段名',
is_pk char(1) comment '是否主键1是',
is_increment char(1) comment '是否自增1是',
is_required char(1) comment '是否必填1是',
is_insert char(1) comment '是否为插入字段1是',
is_edit char(1) comment '是否编辑字段1是',
is_list char(1) comment '是否列表字段1是',
is_query char(1) comment '是否查询字段1是',
query_type varchar(200) default 'EQ' comment '查询方式(等于、不等于、大于、小于、范围)',
html_type varchar(200) comment '显示类型(文本框、文本域、下拉框、复选框、单选框、日期控件)',
dict_type varchar(200) default '' comment '字典类型',
sort int comment '排序',
create_dept bigint(20) default null comment '创建部门',
create_by bigint(20) default null comment '创建者',
create_time datetime comment '创建时间',
update_by bigint(20) default null comment '更新者',
update_time datetime comment '更新时间',
primary key (column_id)
) engine=innodb comment = '代码生成业务表字段';

20
pom.xml
View File

@ -38,6 +38,9 @@
<hutool.version>5.8.18</hutool.version>
<mapstruct-plus.version>1.3.1</mapstruct-plus.version>
<spring-brick.version>3.1.4</spring-brick.version>
<yitter.version>1.0.6</yitter.version>
<velocity.version>2.3</velocity.version>
</properties>
<dependencyManagement>
@ -340,6 +343,12 @@
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>cc.iotkit</groupId>
<artifactId>iot-generator</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>cc.iotkit</groupId>
<artifactId>iot-message-notify</artifactId>
@ -406,6 +415,17 @@
<version>${iot-iita-core.version}</version>
</dependency>
<dependency>
<groupId>com.github.yitter</groupId>
<artifactId>yitter-idgenerator</artifactId>
<version>${yitter.version}</version>
</dependency>
<!-- velocity代码生成使用模板 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>