提交 3f80af66 编写于 作者: D dqjdda

代码生成器基础升级完成,剩余:预览,打包下载,关联实体未完成

上级 41b562f3
package me.zhengjie.domain; package me.zhengjie.domain;
import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import me.zhengjie.utils.GenUtil;
import javax.persistence.*; import javax.persistence.*;
/** /**
...@@ -60,14 +59,20 @@ public class ColumnInfo { ...@@ -60,14 +59,20 @@ public class ColumnInfo {
// 关联表名 // 关联表名
private String joinName; private String joinName;
// 日期注解
private String dateAnnotation;
public ColumnInfo(String tableName, String columnName, Boolean notNull, String columnType, String remark, String keyType, String extra) { public ColumnInfo(String tableName, String columnName, Boolean notNull, String columnType, String remark, String keyType, String extra) {
this.tableName = tableName; this.tableName = tableName;
this.columnName = columnName; this.columnName = columnName;
this.columnType = columnType; this.columnType = columnType;
this.keyType = keyType; this.keyType = keyType;
this.extra = extra; this.extra = extra;
this.remark = remark;
this.notNull = notNull; this.notNull = notNull;
if(GenUtil.PK.equalsIgnoreCase(keyType) && GenUtil.EXTRA.equalsIgnoreCase(extra)){
this.notNull = false;
}
this.remark = remark;
this.listShow = true; this.listShow = true;
this.formShow = true; this.formShow = true;
} }
......
...@@ -34,6 +34,12 @@ public class GeneratorController { ...@@ -34,6 +34,12 @@ public class GeneratorController {
this.genConfigService = genConfigService; this.genConfigService = genConfigService;
} }
@ApiOperation("查询数据库数据")
@GetMapping(value = "/tables/all")
public ResponseEntity getTables(){
return new ResponseEntity<>(generatorService.getTables(), HttpStatus.OK);
}
@ApiOperation("查询数据库数据") @ApiOperation("查询数据库数据")
@GetMapping(value = "/tables") @GetMapping(value = "/tables")
public ResponseEntity getTables(@RequestParam(defaultValue = "") String name, public ResponseEntity getTables(@RequestParam(defaultValue = "") String name,
...@@ -55,18 +61,22 @@ public class GeneratorController { ...@@ -55,18 +61,22 @@ public class GeneratorController {
@ApiOperation("保存字段数据") @ApiOperation("保存字段数据")
@PutMapping @PutMapping
public ResponseEntity save(@RequestBody List<ColumnInfo> columnInfos){ public ResponseEntity save(@RequestBody List<ColumnInfo> columnInfos){
// 异步同步表信息
generatorService.save(columnInfos); generatorService.save(columnInfos);
return new ResponseEntity(HttpStatus.OK); return new ResponseEntity(HttpStatus.OK);
} }
@ApiOperation("生成代码") @ApiOperation("生成代码")
@PostMapping @PostMapping(value = "/{tableName}/{type}")
public ResponseEntity generator(@RequestBody List<ColumnInfo> columnInfos, @RequestParam String tableName){ public ResponseEntity generator(@PathVariable String tableName, @PathVariable Integer type){
if(!generatorEnabled){ if(!generatorEnabled){
throw new BadRequestException("此环境不允许生成代码!"); throw new BadRequestException("此环境不允许生成代码!");
} }
generatorService.generator(columnInfos,genConfigService.find(tableName),tableName); switch (type){
// 生成代码
case 0: generatorService.generator(genConfigService.find(tableName), generatorService.getColumns(tableName));
break;
default: break;
}
return new ResponseEntity(HttpStatus.OK); return new ResponseEntity(HttpStatus.OK);
} }
} }
...@@ -27,14 +27,6 @@ public interface GeneratorService { ...@@ -27,14 +27,6 @@ public interface GeneratorService {
*/ */
List<ColumnInfo> getColumns(String name); List<ColumnInfo> getColumns(String name);
/**
* 生成代码
* @param columnInfos 表字段数据
* @param genConfig 代码生成配置
* @param tableName 表名
*/
void generator(List<ColumnInfo> columnInfos, GenConfig genConfig, String tableName);
/** /**
* 同步表数据 * 同步表数据
* @param columnInfos / * @param columnInfos /
...@@ -47,4 +39,18 @@ public interface GeneratorService { ...@@ -47,4 +39,18 @@ public interface GeneratorService {
* @param columnInfos / * @param columnInfos /
*/ */
void save(List<ColumnInfo> columnInfos); void save(List<ColumnInfo> columnInfos);
/**
* 获取所有table
* @return /
*/
Object getTables();
/**
* 代码生成
* @param genConfig 配置信息
* @param columns 字段信息
* @return /
*/
Object generator(GenConfig genConfig, List<ColumnInfo> columns);
} }
...@@ -24,6 +24,7 @@ import java.util.List; ...@@ -24,6 +24,7 @@ import java.util.List;
* @date 2019-01-02 * @date 2019-01-02
*/ */
@Service @Service
@SuppressWarnings("all")
public class GeneratorServiceImpl implements GeneratorService { public class GeneratorServiceImpl implements GeneratorService {
@PersistenceContext @PersistenceContext
...@@ -36,7 +37,16 @@ public class GeneratorServiceImpl implements GeneratorService { ...@@ -36,7 +37,16 @@ public class GeneratorServiceImpl implements GeneratorService {
} }
@Override @Override
@SuppressWarnings("all") public Object getTables() {
// 使用预编译防止sql注入
String sql = "select table_name ,create_time , engine, table_collation, table_comment from information_schema.tables " +
"where table_schema = (select database()) " +
"order by create_time desc";
Query query = em.createNativeQuery(sql);
return query.getResultList();
}
@Override
public Object getTables(String name, int[] startEnd) { public Object getTables(String name, int[] startEnd) {
// 使用预编译防止sql注入 // 使用预编译防止sql注入
String sql = "select table_name ,create_time , engine, table_collation, table_comment from information_schema.tables " + String sql = "select table_name ,create_time , engine, table_collation, table_comment from information_schema.tables " +
...@@ -68,7 +78,6 @@ public class GeneratorServiceImpl implements GeneratorService { ...@@ -68,7 +78,6 @@ public class GeneratorServiceImpl implements GeneratorService {
} }
} }
@SuppressWarnings("all")
public List<ColumnInfo> query(String tableName){ public List<ColumnInfo> query(String tableName){
// 使用预编译防止sql注入 // 使用预编译防止sql注入
String sql = "select column_name, is_nullable, data_type, column_comment, column_key, extra from information_schema.columns " + String sql = "select column_name, is_nullable, data_type, column_comment, column_key, extra from information_schema.columns " +
...@@ -104,14 +113,15 @@ public class GeneratorServiceImpl implements GeneratorService { ...@@ -104,14 +113,15 @@ public class GeneratorServiceImpl implements GeneratorService {
} }
@Override @Override
public void generator(List<ColumnInfo> columnInfos, GenConfig genConfig, String tableName) { public Object generator(GenConfig genConfig, List<ColumnInfo> columns) {
if(genConfig.getId() == null){ if(genConfig.getId() == null){
throw new BadRequestException("请先配置生成器"); throw new BadRequestException("请先配置生成器");
} }
try { try {
GenUtil.generatorCode(columnInfos,genConfig,tableName); GenUtil.generatorCode(columns,genConfig);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
return null;
} }
} }
...@@ -28,9 +28,9 @@ public class GenUtil { ...@@ -28,9 +28,9 @@ public class GenUtil {
private static final String BIGDECIMAL = "BigDecimal"; private static final String BIGDECIMAL = "BigDecimal";
private static final String PK = "PRI"; public static final String PK = "PRI";
private static final String EXTRA = "auto_increment"; public static final String EXTRA = "auto_increment";
/** /**
* 获取后端代码模板名称 * 获取后端代码模板名称
...@@ -61,85 +61,161 @@ public class GenUtil { ...@@ -61,85 +61,161 @@ public class GenUtil {
return templateNames; return templateNames;
} }
/** public static void generatorCode(List<ColumnInfo> columnInfos, GenConfig genConfig) throws IOException {
* 生成代码 // 存储模版字段数据
* @param columnInfos 表元数据 Map<String,Object> genMap = new HashMap<>();
* @param genConfig 生成代码的参数配置,如包路径,作者 // 包名称
*/ genMap.put("package",genConfig.getPack());
public static void generatorCode(List<ColumnInfo> columnInfos, GenConfig genConfig, String tableName) throws IOException { // 模块名称
Map<String,Object> map = new HashMap<>(); genMap.put("moduleName",genConfig.getModuleName());
map.put("package",genConfig.getPack()); // 作者
map.put("moduleName",genConfig.getModuleName()); genMap.put("author",genConfig.getAuthor());
map.put("author",genConfig.getAuthor()); // 创建日期
map.put("date", LocalDate.now().toString()); genMap.put("date", LocalDate.now().toString());
map.put("tableName",tableName); // 表名
String className = StringUtils.toCapitalizeCamelCase(tableName); genMap.put("tableName",genConfig.getTableName());
String changeClassName = StringUtils.toCamelCase(tableName); // 大写开头的类名
String className = StringUtils.toCapitalizeCamelCase(genConfig.getTableName());
// 小写开头的类名
String changeClassName = StringUtils.toCamelCase(genConfig.getTableName());
// 判断是否去除表前缀 // 判断是否去除表前缀
if (StringUtils.isNotEmpty(genConfig.getPrefix())) { if (StringUtils.isNotEmpty(genConfig.getPrefix())) {
className = StringUtils.toCapitalizeCamelCase(StrUtil.removePrefix(tableName,genConfig.getPrefix())); className = StringUtils.toCapitalizeCamelCase(StrUtil.removePrefix(genConfig.getTableName(),genConfig.getPrefix()));
changeClassName = StringUtils.toCamelCase(StrUtil.removePrefix(tableName,genConfig.getPrefix())); changeClassName = StringUtils.toCamelCase(StrUtil.removePrefix(genConfig.getTableName(),genConfig.getPrefix()));
} }
map.put("className", className); // 保存类名
map.put("upperCaseClassName", className.toUpperCase()); genMap.put("className", className);
map.put("changeClassName", changeClassName); // 保存小写开头的类名
map.put("hasTimestamp",false); genMap.put("changeClassName", changeClassName);
map.put("queryHasTimestamp",false); // 存在 Timestamp 字段
map.put("queryHasBigDecimal",false); genMap.put("hasTimestamp",false);
map.put("hasBigDecimal",false); // 查询类中存在 Timestamp 字段
map.put("hasQuery",false); genMap.put("queryHasTimestamp",false);
map.put("auto",false); // 存在 BigDecimal 字段
genMap.put("hasBigDecimal",false);
// 查询类中存在 BigDecimal 字段
genMap.put("queryHasBigDecimal",false);
// 是否需要创建查询
genMap.put("hasQuery",false);
// 自增主键
genMap.put("auto",false);
// 存在字典
genMap.put("hasDict",false);
// 存在日期注解
genMap.put("hasDateAnnotation",false);
// 保存字段信息
List<Map<String,Object>> columns = new ArrayList<>(); List<Map<String,Object>> columns = new ArrayList<>();
// 保存查询字段的信息
List<Map<String,Object>> queryColumns = new ArrayList<>(); List<Map<String,Object>> queryColumns = new ArrayList<>();
// 存储字典信息
List<String> dicts = new ArrayList<>();
// 存储 DateRange 信息
List<Map<String,Object>> dateRanges = new ArrayList<>();
// 存储不为空的字段信息
List<Map<String,Object>> isNotNullColumns = new ArrayList<>();
for (ColumnInfo column : columnInfos) { for (ColumnInfo column : columnInfos) {
Map<String,Object> listMap = new HashMap<>(); Map<String,Object> listMap = new HashMap<>();
listMap.put("columnComment",column.getRemark()); // 字段描述
listMap.put("remark",column.getRemark());
// 字段类型
listMap.put("columnKey",column.getKeyType()); listMap.put("columnKey",column.getKeyType());
// 主键类型
String colType = ColUtil.cloToJava(column.getColumnType().toString()); String colType = ColUtil.cloToJava(column.getColumnType());
// 小写开头的字段名
String changeColumnName = StringUtils.toCamelCase(column.getColumnName().toString()); String changeColumnName = StringUtils.toCamelCase(column.getColumnName().toString());
// 大写开头的字段名
String capitalColumnName = StringUtils.toCapitalizeCamelCase(column.getColumnName().toString()); String capitalColumnName = StringUtils.toCapitalizeCamelCase(column.getColumnName().toString());
if(PK.equals(column.getKeyType())){ if(PK.equals(column.getKeyType())){
map.put("pkColumnType",colType); // 存储主键类型
map.put("pkChangeColName",changeColumnName); genMap.put("pkColumnType",colType);
map.put("pkCapitalColName",capitalColumnName); // 存储小写开头的字段名
genMap.put("pkChangeColName",changeColumnName);
// 存储大写开头的字段名
genMap.put("pkCapitalColName",capitalColumnName);
} }
// 是否存在 Timestamp 类型的字段
if(TIMESTAMP.equals(colType)){ if(TIMESTAMP.equals(colType)){
map.put("hasTimestamp",true); genMap.put("hasTimestamp",true);
} }
// 是否存在 BigDecimal 类型的字段
if(BIGDECIMAL.equals(colType)){ if(BIGDECIMAL.equals(colType)){
map.put("hasBigDecimal",true); genMap.put("hasBigDecimal",true);
} }
// 主键是否自增
if(EXTRA.equals(column.getExtra())){ if(EXTRA.equals(column.getExtra())){
map.put("auto",true); genMap.put("auto",true);
}
// 主键存在字典
if(StringUtils.isNotBlank(column.getDictName())){
genMap.put("hasDict",true);
dicts.add(column.getDictName());
} }
// 存储字段类型
listMap.put("columnType",colType); listMap.put("columnType",colType);
// 存储字原始段名称
listMap.put("columnName",column.getColumnName()); listMap.put("columnName",column.getColumnName());
listMap.put("isNullable",column.getNotNull()); // 不为空
listMap.put("istNotNull",column.getNotNull());
// 字段列表显示
listMap.put("columnShow",column.getListShow()); listMap.put("columnShow",column.getListShow());
// 表单显示
listMap.put("formShow",column.getFormShow());
// 表单组件类型
listMap.put("formType",column.getFormType());
// 小写开头的字段名称
listMap.put("changeColumnName",changeColumnName); listMap.put("changeColumnName",changeColumnName);
//大写开头的字段名称
listMap.put("capitalColumnName",capitalColumnName); listMap.put("capitalColumnName",capitalColumnName);
// 字典名称
listMap.put("dictName",column.getDictName());
// 关联字段
listMap.put("joinName",column.getJoinName());
// 日期注解
listMap.put("dateAnnotation",column.getDateAnnotation());
if(StringUtils.isNotBlank(column.getDateAnnotation())){
genMap.put("hasDateAnnotation",true);
}
// 添加非空字段信息
if(column.getNotNull()){
isNotNullColumns.add(listMap);
}
// 判断是否有查询,如有则把查询的字段set进columnQuery // 判断是否有查询,如有则把查询的字段set进columnQuery
if(!StringUtils.isBlank(column.getQueryType())){ if(!StringUtils.isBlank(column.getQueryType())){
listMap.put("columnQuery",column.getQueryType()); // 查询类型
map.put("hasQuery",true); listMap.put("queryType",column.getQueryType());
// 是否存在查询
genMap.put("hasQuery",true);
if(TIMESTAMP.equals(colType)){ if(TIMESTAMP.equals(colType)){
map.put("queryHasTimestamp",true); // 查询中存储 Timestamp 类型
genMap.put("queryHasTimestamp",true);
} }
if(BIGDECIMAL.equals(colType)){ if(BIGDECIMAL.equals(colType)){
map.put("queryHasBigDecimal",true); // 查询中存储 BigDecimal 类型
genMap.put("queryHasBigDecimal",true);
}
if("DateRange".equalsIgnoreCase(column.getQueryType())){
dateRanges.add(listMap);
} else {
// 添加到查询列表中
queryColumns.add(listMap);
} }
queryColumns.add(listMap);
} }
// 添加到字段列表中
columns.add(listMap); columns.add(listMap);
} }
map.put("columns",columns); // 保存字段列表
map.put("queryColumns",queryColumns); genMap.put("columns",columns);
// 保存查询列表
genMap.put("queryColumns",queryColumns);
// 保存字段列表
genMap.put("dicts",dicts);
// 保存查询列表
genMap.put("dateRanges",dateRanges);
// 保存非空字段信息
genMap.put("isNotNullColumns",isNotNullColumns);
TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
// 生成后端代码 // 生成后端代码
List<String> templates = getAdminTemplateNames(); List<String> templates = getAdminTemplateNames();
for (String templateName : templates) { for (String templateName : templates) {
...@@ -154,14 +230,14 @@ public class GenUtil { ...@@ -154,14 +230,14 @@ public class GenUtil {
continue; continue;
} }
// 生成代码 // 生成代码
genFile(file, template, map); genFile(file, template, genMap);
} }
// 生成前端代码 // 生成前端代码
templates = getFrontTemplateNames(); templates = getFrontTemplateNames();
for (String templateName : templates) { for (String templateName : templates) {
Template template = engine.getTemplate("generator/front/"+templateName+".ftl"); Template template = engine.getTemplate("generator/front/"+templateName+".ftl");
String filePath = getFrontFilePath(templateName,genConfig,map.get("changeClassName").toString()); String filePath = getFrontFilePath(templateName,genConfig,genMap.get("changeClassName").toString());
assert filePath != null; assert filePath != null;
File file = new File(filePath); File file = new File(filePath);
...@@ -171,7 +247,7 @@ public class GenUtil { ...@@ -171,7 +247,7 @@ public class GenUtil {
continue; continue;
} }
// 生成代码 // 生成代码
genFile(file, template, map); genFile(file, template, genMap);
} }
} }
......
package me.zhengjie.gen.domain;
import lombok.Data;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import javax.persistence.*;
import javax.validation.constraints.*;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.annotations.*;
import java.sql.Timestamp;
import java.io.Serializable;
/**
* @author Zheng Jie
* @date 2019-11-19
*/
@Entity
@Data
@Table(name="gen_test")
public class GenTest implements Serializable {
// ID
@Id
@Column(name = "id")
private Long id;
// 名称
@Column(name = "name",nullable = false)
@NotBlank
private String name;
// 状态
@Column(name = "status",nullable = false)
@NotNull
private Boolean status;
// 日期
@Column(name = "date",nullable = false)
@NotNull
private Timestamp date;
// 创建日期
@Column(name = "create_time")
@CreationTimestamp
private Timestamp createTime;
public void copy(GenTest source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}
\ No newline at end of file
package me.zhengjie.gen.repository;
import me.zhengjie.gen.domain.GenTest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author Zheng Jie
* @date 2019-11-19
*/
public interface GenTestRepository extends JpaRepository<GenTest, Long>, JpaSpecificationExecutor<GenTest> {
}
\ No newline at end of file
package me.zhengjie.gen.rest;
import me.zhengjie.aop.log.Log;
import me.zhengjie.gen.domain.GenTest;
import me.zhengjie.gen.service.GenTestService;
import me.zhengjie.gen.service.dto.GenTestQueryCriteria;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @author Zheng Jie
* @date 2019-11-19
*/
@Api(tags = "GenTest管理")
@RestController
@RequestMapping("/api/genTest")
public class GenTestController {
private final GenTestService genTestService;
public GenTestController(GenTestService genTestService) {
this.genTestService = genTestService;
}
@Log("导出数据")
@ApiOperation("导出数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('genTest:list')")
public void download(HttpServletResponse response, GenTestQueryCriteria criteria) throws IOException {
genTestService.download(genTestService.queryAll(criteria), response);
}
@GetMapping
@Log("查询GenTest")
@ApiOperation("查询GenTest")
@PreAuthorize("@el.check('genTest:list')")
public ResponseEntity getGenTests(GenTestQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(genTestService.queryAll(criteria,pageable),HttpStatus.OK);
}
@PostMapping
@Log("新增GenTest")
@ApiOperation("新增GenTest")
@PreAuthorize("@el.check('genTest:add')")
public ResponseEntity create(@Validated @RequestBody GenTest resources){
return new ResponseEntity<>(genTestService.create(resources),HttpStatus.CREATED);
}
@PutMapping
@Log("修改GenTest")
@ApiOperation("修改GenTest")
@PreAuthorize("@el.check('genTest:edit')")
public ResponseEntity update(@Validated @RequestBody GenTest resources){
genTestService.update(resources);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
@DeleteMapping(value = "/{id}")
@Log("删除GenTest")
@ApiOperation("删除GenTest")
@PreAuthorize("@el.check('genTest:del')")
public ResponseEntity delete(@PathVariable Long id){
genTestService.delete(id);
return new ResponseEntity(HttpStatus.OK);
}
}
\ No newline at end of file
package me.zhengjie.gen.service;
import me.zhengjie.gen.domain.GenTest;
import me.zhengjie.gen.service.dto.GenTestDTO;
import me.zhengjie.gen.service.dto.GenTestQueryCriteria;
import org.springframework.data.domain.Pageable;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @author Zheng Jie
* @date 2019-11-19
*/
public interface GenTestService {
/**
* 查询数据分页
* @param criteria 条件参数
* @param pageable 分页参数
* @return Map<String,Object>
*/
Map<String,Object> queryAll(GenTestQueryCriteria criteria, Pageable pageable);
/**
* 查询所有数据不分页
* @param criteria 条件参数
* @return List<GenTestDTO>
*/
List<GenTestDTO> queryAll(GenTestQueryCriteria criteria);
/**
* 根据ID查询
* @param id ID
* @return GenTestDTO
*/
GenTestDTO findById(Long id);
GenTestDTO create(GenTest resources);
void update(GenTest resources);
void delete(Long id);
void download(List<GenTestDTO> all, HttpServletResponse response) throws IOException;
}
\ No newline at end of file
package me.zhengjie.gen.service.dto;
import lombok.Data;
import java.sql.Timestamp;
import java.io.Serializable;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
/**
* @author Zheng Jie
* @date 2019-11-19
*/
@Data
public class GenTestDTO implements Serializable {
// ID
// 处理精度丢失问题
@JsonSerialize(using= ToStringSerializer.class)
private Long id;
// 名称
private String name;
// 状态
private Boolean status;
// 日期
private Timestamp date;
// 创建日期
private Timestamp createTime;
}
\ No newline at end of file
package me.zhengjie.gen.service.dto;
import lombok.Data;
import java.sql.Timestamp;
import me.zhengjie.annotation.Query;
/**
* @author Zheng Jie
* @date 2019-11-19
*/
@Data
public class GenTestQueryCriteria{
// 模糊
@Query(type = Query.Type.INNER_LIKE)
private String name;
// 精确
@Query
private Boolean status;
// 时间段查询
@Query(type = Query.Type.GREATER_THAN, propName = "date")
private Timestamp dateStart;
@Query(type = Query.Type.LESS_THAN, propName = "date")
private Timestamp dateEnd;
// 时间段查询
@Query(type = Query.Type.GREATER_THAN, propName = "createTime")
private Timestamp createTimeStart;
@Query(type = Query.Type.LESS_THAN, propName = "createTime")
private Timestamp createTimeEnd;
}
\ No newline at end of file
package me.zhengjie.gen.service.impl;
import me.zhengjie.gen.domain.GenTest;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.gen.repository.GenTestRepository;
import me.zhengjie.gen.service.GenTestService;
import me.zhengjie.gen.service.dto.GenTestDTO;
import me.zhengjie.gen.service.dto.GenTestQueryCriteria;
import me.zhengjie.gen.service.mapper.GenTestMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
/**
* @author Zheng Jie
* @date 2019-11-19
*/
@Service
@CacheConfig(cacheNames = "genTest")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class GenTestServiceImpl implements GenTestService {
private final GenTestRepository genTestRepository;
private final GenTestMapper genTestMapper;
public GenTestServiceImpl(GenTestRepository genTestRepository, GenTestMapper genTestMapper) {
this.genTestRepository = genTestRepository;
this.genTestMapper = genTestMapper;
}
@Override
@Cacheable
public Map<String,Object> queryAll(GenTestQueryCriteria criteria, Pageable pageable){
Page<GenTest> page = genTestRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPage(page.map(genTestMapper::toDto));
}
@Override
@Cacheable
public List<GenTestDTO> queryAll(GenTestQueryCriteria criteria){
return genTestMapper.toDto(genTestRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
}
@Override
@Cacheable(key = "#p0")
public GenTestDTO findById(Long id) {
GenTest genTest = genTestRepository.findById(id).orElseGet(GenTest::new);
ValidationUtil.isNull(genTest.getId(),"GenTest","id",id);
return genTestMapper.toDto(genTest);
}
@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public GenTestDTO create(GenTest resources) {
Snowflake snowflake = IdUtil.createSnowflake(1, 1);
resources.setId(snowflake.nextId());
return genTestMapper.toDto(genTestRepository.save(resources));
}
@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public void update(GenTest resources) {
GenTest genTest = genTestRepository.findById(resources.getId()).orElseGet(GenTest::new);
ValidationUtil.isNull( genTest.getId(),"GenTest","id",resources.getId());
genTest.copy(resources);
genTestRepository.save(genTest);
}
@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public void delete(Long id) {
genTestRepository.deleteById(id);
}
@Override
public void download(List<GenTestDTO> all, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (GenTestDTO genTest : all) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("名称", genTest.getName());
map.put("状态", genTest.getStatus());
map.put("日期", genTest.getDate());
map.put("创建日期", genTest.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
}
\ No newline at end of file
package me.zhengjie.gen.service.mapper;
import me.zhengjie.base.BaseMapper;
import me.zhengjie.gen.domain.GenTest;
import me.zhengjie.gen.service.dto.GenTestDTO;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author Zheng Jie
* @date 2019-11-19
*/
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface GenTestMapper extends BaseMapper<GenTestDTO, GenTest> {
}
\ No newline at end of file
...@@ -23,8 +23,8 @@ public class ${className}DTO implements Serializable { ...@@ -23,8 +23,8 @@ public class ${className}DTO implements Serializable {
<#if columns??> <#if columns??>
<#list columns as column> <#list columns as column>
<#if column.columnComment != ''> <#if column.remark != ''>
// ${column.columnComment} // ${column.remark}
</#if> </#if>
<#if column.columnKey = 'PRI'> <#if column.columnKey = 'PRI'>
<#if !auto && pkColumnType = 'Long'> <#if !auto && pkColumnType = 'Long'>
......
...@@ -4,6 +4,14 @@ import lombok.Data; ...@@ -4,6 +4,14 @@ import lombok.Data;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions; import cn.hutool.core.bean.copier.CopyOptions;
import javax.persistence.*; import javax.persistence.*;
<#if isNotNullColumns??>
import javax.validation.constraints.*;
</#if>
<#if hasDateAnnotation>
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.annotations.*;
</#if>
<#if hasTimestamp> <#if hasTimestamp>
import java.sql.Timestamp; import java.sql.Timestamp;
</#if> </#if>
...@@ -23,8 +31,8 @@ public class ${className} implements Serializable { ...@@ -23,8 +31,8 @@ public class ${className} implements Serializable {
<#if columns??> <#if columns??>
<#list columns as column> <#list columns as column>
<#if column.columnComment != ''> <#if column.remark != ''>
// ${column.columnComment} // ${column.remark}
</#if> </#if>
<#if column.columnKey = 'PRI'> <#if column.columnKey = 'PRI'>
@Id @Id
...@@ -32,7 +40,21 @@ public class ${className} implements Serializable { ...@@ -32,7 +40,21 @@ public class ${className} implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
</#if> </#if>
</#if> </#if>
@Column(name = "${column.columnName}"<#if column.columnKey = 'UNI'>,unique = true</#if><#if column.isNullable = 'NO' && column.columnKey != 'PRI'>,nullable = false</#if>) @Column(name = "${column.columnName}"<#if column.columnKey = 'UNI'>,unique = true</#if><#if column.istNotNull && column.columnKey != 'PRI'>,nullable = false</#if>)
<#if column.istNotNull && column.columnKey != 'PRI'>
<#if column.columnType = 'String'>
@NotBlank
<#else>
@NotNull
</#if>
</#if>
<#if column.dateAnnotation??>
<#if column.dateAnnotation = 'CreationTimestamp'>
@CreationTimestamp
<#else>
@UpdateTimestamp
</#if>
</#if>
private ${column.columnType} ${column.changeColumnName}; private ${column.columnType} ${column.changeColumnName};
</#list> </#list>
</#if> </#if>
......
...@@ -20,15 +20,42 @@ public class ${className}QueryCriteria{ ...@@ -20,15 +20,42 @@ public class ${className}QueryCriteria{
<#if queryColumns??> <#if queryColumns??>
<#list queryColumns as column> <#list queryColumns as column>
<#if column.columnQuery = '1'> <#if column.queryType = '='>
// 模糊
@Query(type = Query.Type.INNER_LIKE)
</#if>
<#if column.columnQuery = '2'>
// 精确 // 精确
@Query @Query
</#if>
private ${column.columnType} ${column.changeColumnName}; private ${column.columnType} ${column.changeColumnName};
</#if>
<#if column.queryType = 'Like'>
// 模糊
@Query(type = Query.Type.INNER_LIKE)
private ${column.columnType} ${column.changeColumnName};
</#if>
<#if column.queryType = '!='>
// 不等于
@Query(type = Query.Type.NOT_EQUAL)
private ${column.columnType} ${column.changeColumnName};
</#if>
<#if column.queryType = '>='>
// 大于等于
@Query(type = Query.Type.GREATER_THAN)
private ${column.columnType} ${column.changeColumnName};
</#if>
<#if column.queryType = '<='>
// 小于等于
@Query(type = Query.Type.LESS_THAN)
private ${column.columnType} ${column.changeColumnName};
</#if>
</#list>
</#if>
<#if dateRanges??>
<#list dateRanges as column>
// 时间段查询
@Query(type = Query.Type.GREATER_THAN, propName = "${column.changeColumnName}")
private ${column.columnType} ${column.changeColumnName}Start;
@Query(type = Query.Type.LESS_THAN, propName = "${column.changeColumnName}")
private ${column.columnType} ${column.changeColumnName}End;
</#list> </#list>
</#if> </#if>
} }
\ No newline at end of file
...@@ -141,8 +141,8 @@ public class ${className}ServiceImpl implements ${className}Service { ...@@ -141,8 +141,8 @@ public class ${className}ServiceImpl implements ${className}Service {
Map<String,Object> map = new LinkedHashMap<>(); Map<String,Object> map = new LinkedHashMap<>();
<#list columns as column> <#list columns as column>
<#if column.columnKey != 'PRI'> <#if column.columnKey != 'PRI'>
<#if column.columnComment != ''> <#if column.remark != ''>
map.put("${column.columnComment}", ${changeClassName}.get${column.capitalColumnName}()); map.put("${column.remark}", ${changeClassName}.get${column.capitalColumnName}());
<#else> <#else>
map.put(" ${column.changeColumnName}", ${changeClassName}.get${column.capitalColumnName}()); map.put(" ${column.changeColumnName}", ${changeClassName}.get${column.capitalColumnName}());
</#if> </#if>
......
<template> <template>
<el-dialog :append-to-body="true" :close-on-click-modal="false" :before-close="cancel" :visible.sync="dialog" :title="isAdd ? '新增' : '编辑'" width="500px"> <el-dialog :append-to-body="true" :close-on-click-modal="false" :before-close="cancel" :visible.sync="dialog" :title="isAdd ? '新增' : '编辑'" width="500px">
<el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px"> <el-form ref="form" :model="form" <#if isNotNullColumns??>:rules="rules"</#if> size="small" label-width="80px">
<#if columns??> <#if columns??>
<#list columns as column> <#list columns as column>
<#if column.changeColumnName != '${pkChangeColName}'> <#if column.formShow>
<el-form-item label="<#if column.columnComment != ''>${column.columnComment}<#else>${column.changeColumnName}</#if>" <#if column.columnKey = 'UNI'>prop="${column.changeColumnName}"</#if>> <el-form-item label="<#if column.remark != ''>${column.remark}<#else>${column.changeColumnName}</#if>" <#if column.istNotNull>prop="${column.changeColumnName}"</#if>>
<#if column.columnType != 'Timestamp'> <#if column.formType = 'Input'>
<el-input v-model="form.${column.changeColumnName}" style="width: 370px;"/> <el-input v-model="form.${column.changeColumnName}" style="width: 370px;"/>
<#else > <#elseif column.formType = 'Textarea'>
<el-input :rows="3" v-model="form.${column.changeColumnName}" type="textarea" style="width: 370px;"/>
<#elseif column.formType = 'Radio'>
<#if column.dictName??>
<el-radio v-for="item in dicts.${column.dictName}" :key="item.id" v-model="form.${column.changeColumnName}" :label="item.value">{{ item.label }}</el-radio>
<#else>
未设置字典,请手动设置 Radio
</#if>
<#elseif column.formType = 'Select'>
<#if column.dictName??>
<el-select v-model="form.${column.changeColumnName}" filterable placeholder="请选择">
<el-option
v-for="item in dicts.${column.dictName}"
:key="item.id"
:label="item.label"
:value="item.value"/>
</el-select>
<#else>
未设置字典,请手动设置 Select
</#if>
<#else>
<el-date-picker v-model="form.${column.changeColumnName}" type="datetime" style="width: 370px;"/> <el-date-picker v-model="form.${column.changeColumnName}" type="datetime" style="width: 370px;"/>
</#if> </#if>
</el-form-item> </el-form-item>
...@@ -29,7 +49,12 @@ export default { ...@@ -29,7 +49,12 @@ export default {
isAdd: { isAdd: {
type: Boolean, type: Boolean,
required: true required: true
}<#if hasDict>,
dicts: {
type: Array,
required: true
} }
</#if>
}, },
data() { data() {
return { return {
...@@ -42,13 +67,15 @@ export default { ...@@ -42,13 +67,15 @@ export default {
</#if> </#if>
}, },
rules: { rules: {
<#list columns as column> <#if isNotNullColumns??>
<#if column.columnKey = 'UNI'> <#list isNotNullColumns as column>
<#if column.istNotNull>
${column.changeColumnName}: [ ${column.changeColumnName}: [
{ required: true, message: 'please enter', trigger: 'blur' } { required: true, message: 'please enter', trigger: 'blur' }
]<#if (column_has_next)>,</#if> ]<#if column_has_next>,</#if>
</#if> </#if>
</#list> </#list>
</#if>
} }
} }
}, },
...@@ -57,10 +84,23 @@ export default { ...@@ -57,10 +84,23 @@ export default {
this.resetForm() this.resetForm()
}, },
doSubmit() { doSubmit() {
this.loading = true <#if isNotNullColumns??>
if (this.isAdd) { this.$refs['form'].validate((valid) => {
this.doAdd() if (valid) {
} else this.doEdit() this.loading = true
if (this.isAdd) {
this.doAdd()
} else this.doEdit()
} else {
return false
}
})
<#else>
this.loading = true
if (this.isAdd) {
this.doAdd()
} else this.doEdit()
</#if>
}, },
doAdd() { doAdd() {
add(this.form).then(res => { add(this.form).then(res => {
......
...@@ -9,6 +9,22 @@ ...@@ -9,6 +9,22 @@
<el-select v-model="query.type" clearable placeholder="类型" class="filter-item" style="width: 130px"> <el-select v-model="query.type" clearable placeholder="类型" class="filter-item" style="width: 130px">
<el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/> <el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
</el-select> </el-select>
<#if dateRanges??>
<#list dateRanges as column>
<#if column.queryType = 'DateRange'>
<el-date-picker
v-model="query.${column.changeColumnName}"
:default-time="['00:00:00','23:59:59']"
type="daterange"
range-separator=":"
class="el-range-editor--small filter-item"
style="height: 30.5px;width: 225px;"
value-format="yyyy-MM-dd HH:mm:ss"
start-placeholder="${column.changeColumnName}Start"
end-placeholder="${column.changeColumnName}End"/>
</#if>
</#list>
</#if>
<el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button> <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>
</#if> </#if>
<!-- 新增 --> <!-- 新增 -->
...@@ -33,16 +49,22 @@ ...@@ -33,16 +49,22 @@
</div> </div>
</div> </div>
<!--表单组件--> <!--表单组件-->
<eForm ref="form" :is-add="isAdd"/> <eForm ref="form" :is-add="isAdd" <#if hasDict>:dicts="dict"</#if>/>
<!--表格渲染--> <!--表格渲染-->
<el-table v-loading="loading" :data="data" size="small" style="width: 100%;"> <el-table v-loading="loading" :data="data" size="small" style="width: 100%;">
<#if columns??> <#if columns??>
<#list columns as column> <#list columns as column>
<#if column.columnShow = 'true'> <#if column.columnShow>
<#if column.columnType != 'Timestamp'> <#if column.dictName??>
<el-table-column prop="${column.changeColumnName}" label="<#if column.columnComment != ''>${column.columnComment}<#else>${column.changeColumnName}</#if>"/> <el-table-column prop="${column.changeColumnName}" label="<#if column.remark != ''>${column.remark}<#else>${column.changeColumnName}</#if>">
<template slot-scope="scope">
{{ dict.label.${column.dictName}[scope.row.${column.changeColumnName}] }}
</template>
</el-table-column>
<#elseif column.columnType != 'Timestamp'>
<el-table-column prop="${column.changeColumnName}" label="<#if column.remark != ''>${column.remark}<#else>${column.changeColumnName}</#if>"/>
<#else> <#else>
<el-table-column prop="${column.changeColumnName}" label="<#if column.columnComment != ''>${column.columnComment}<#else>${column.changeColumnName}</#if>"> <el-table-column prop="${column.changeColumnName}" label="<#if column.remark != ''>${column.remark}<#else>${column.changeColumnName}</#if>">
<template slot-scope="scope"> <template slot-scope="scope">
<span>{{ parseTime(scope.row.${column.changeColumnName}) }}</span> <span>{{ parseTime(scope.row.${column.changeColumnName}) }}</span>
</template> </template>
...@@ -91,6 +113,9 @@ import eForm from './form' ...@@ -91,6 +113,9 @@ import eForm from './form'
export default { export default {
components: { eForm }, components: { eForm },
mixins: [initData], mixins: [initData],
<#if hasDict>
dicts: [<#if hasDict??><#list dicts as dict>'${dict}'<#if dict_has_next>, </#if></#list></#if>],
</#if>
data() { data() {
return { return {
delLoading: false, delLoading: false,
...@@ -98,7 +123,9 @@ export default { ...@@ -98,7 +123,9 @@ export default {
queryTypeOptions: [ queryTypeOptions: [
<#if queryColumns??> <#if queryColumns??>
<#list queryColumns as column> <#list queryColumns as column>
{ key: '${column.changeColumnName}', display_name: '<#if column.columnComment != ''>${column.columnComment}<#else>${column.changeColumnName}</#if>' }<#if column_has_next>,</#if> <#if column.queryType != 'DateRange'>
{ key: '${column.changeColumnName}', display_name: '<#if column.remark != ''>${column.remark}<#else>${column.changeColumnName}</#if>' }<#if column_has_next>,</#if>
</#if>
</#list> </#list>
</#if> </#if>
] ]
...@@ -124,6 +151,16 @@ export default { ...@@ -124,6 +151,16 @@ export default {
const type = query.type const type = query.type
const value = query.value const value = query.value
if (type && value) { this.params[type] = value } if (type && value) { this.params[type] = value }
<#if dateRanges??>
<#list dateRanges as column>
<#if column.queryType = 'DateRange'>
if (query.${column.changeColumnName}) {
this.params['${column.changeColumnName}Start'] = query.${column.changeColumnName}[0]
this.params['${column.changeColumnName}End'] = query.${column.changeColumnName}[1]
}
</#if>
</#list>
</#if>
</#if> </#if>
return true return true
}, },
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册