Commit c4fc3da1 authored by zhengjie's avatar zhengjie
Browse files

代码生成器优化,新增多数据字典支持,用户修改密码优化

parent 375cdf4d
......@@ -31,6 +31,7 @@ public @interface Query {
Join join() default Join.LEFT;
enum Type {
/** jie 2019/6/4 相等 */
EQUAL
/** Dong ZhaoYang 2017/8/7 大于等于 */
, GREATER_THAN
......
......@@ -101,7 +101,9 @@ public class QueryHelp {
private static <T, R> Expression<T> getExpression(String attributeName, Join join, Root<R> root) {
if (ObjectUtil.isNotEmpty(join)) {
return join.get(attributeName);
} else return root.get(attributeName);
} else {
return root.get(attributeName);
}
}
@SuppressWarnings("unchecked")
......
......@@ -19,4 +19,15 @@ public class TableInfo {
/** 创建日期 **/
private Object createTime;
// 数据库引擎
private Object engine;
// 编码集
private Object coding;
// 备注
private Object remark;
}
......@@ -23,6 +23,7 @@ public interface GenConfigService {
/**
* update
* @param genConfig
* @return
*/
@CacheEvict(allEntries = true)
GenConfig update(GenConfig genConfig);
......
package me.zhengjie.service.impl;
import cn.hutool.core.util.ObjectUtil;
import me.zhengjie.domain.GenConfig;
import me.zhengjie.domain.vo.ColumnInfo;
import me.zhengjie.domain.vo.TableInfo;
......@@ -7,8 +8,8 @@ import me.zhengjie.exception.BadRequestException;
import me.zhengjie.service.GeneratorService;
import me.zhengjie.utils.GenUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
......@@ -28,20 +29,18 @@ public class GeneratorServiceImpl implements GeneratorService {
@Override
public Object getTables(String name, int[] startEnd) {
StringBuilder sql = new StringBuilder("select table_name tableName,create_time createTime from information_schema.tables where table_schema = (select database()) ");
if(!ObjectUtils.isEmpty(name)){
sql.append("and table_name like '%"+name+"%' ");
}
sql.append("order by table_name");
Query query = em.createNativeQuery(sql.toString());
// 使用预编译防止sql注入
String sql = "select table_name ,create_time , engine, table_collation, table_comment from information_schema.tables " +
"where table_schema = (select database()) " +
"and table_name like ? order by create_time desc";
Query query = em.createNativeQuery(sql);
query.setFirstResult(startEnd[0]);
query.setMaxResults(startEnd[1]-startEnd[0]);
System.out.println(sql.toString());
query.setParameter(1, StringUtils.isNotBlank(name) ? ("%" + name + "%") : "%%");
List<Object[]> result = query.getResultList();
List<TableInfo> tableInfos = new ArrayList<>();
for (Object[] obj : result) {
tableInfos.add(new TableInfo(obj[0],obj[1]));
tableInfos.add(new TableInfo(obj[0],obj[1],obj[2],obj[3], ObjectUtil.isNotEmpty(obj[4])? obj[4] : "-"));
}
Query query1 = em.createNativeQuery("SELECT COUNT(*) from information_schema.tables where table_schema = (select database())");
Object totalElements = query1.getSingleResult();
......@@ -50,12 +49,11 @@ public class GeneratorServiceImpl implements GeneratorService {
@Override
public Object getColumns(String name) {
StringBuilder sql = new StringBuilder("select column_name, is_nullable, data_type, column_comment, column_key, extra from information_schema.columns where ");
if(!ObjectUtils.isEmpty(name)){
sql.append("table_name = '"+name+"' ");
}
sql.append("and table_schema = (select database()) order by ordinal_position");
Query query = em.createNativeQuery(sql.toString());
// 使用预编译防止sql注入
String sql = "select column_name, is_nullable, data_type, column_comment, column_key, extra from information_schema.columns " +
"where table_name = ? and table_schema = (select database()) order by ordinal_position";
Query query = em.createNativeQuery(sql);
query.setParameter(1, StringUtils.isNotBlank(name) ? name : null);
List<Object[]> result = query.getResultList();
List<ColumnInfo> columnInfos = new ArrayList<>();
for (Object[] obj : result) {
......
......@@ -57,8 +57,6 @@ public class GenUtil {
List<String> templateNames = new ArrayList<>();
templateNames.add("api");
templateNames.add("index");
templateNames.add("header");
templateNames.add("edit");
templateNames.add("eForm");
return templateNames;
}
......@@ -174,8 +172,8 @@ public class GenUtil {
* 定义后端文件路径以及名称
*/
public static String getAdminFilePath(String templateName, GenConfig genConfig, String className) {
String ProjectPath = System.getProperty("user.dir") + File.separator + genConfig.getModuleName();
String packagePath = ProjectPath + File.separator + "src" +File.separator+ "main" + File.separator + "java" + File.separator;
String projectPath = System.getProperty("user.dir") + File.separator + genConfig.getModuleName();
String packagePath = projectPath + File.separator + "src" +File.separator+ "main" + File.separator + "java" + File.separator;
if (!ObjectUtils.isEmpty(genConfig.getPack())) {
packagePath += genConfig.getPack().replace(".", File.separator) + File.separator;
}
......@@ -229,16 +227,8 @@ public class GenUtil {
return path + File.separator + "index.vue";
}
if ("header".equals(templateName)) {
return path + File.separator + "module" + File.separator + "header.vue";
}
if ("edit".equals(templateName)) {
return path + File.separator + "module" + File.separator + "edit.vue";
}
if ("eForm".equals(templateName)) {
return path + File.separator + "module" + File.separator + "form.vue";
return path + File.separator + File.separator + "form.vue";
}
return null;
}
......
......@@ -22,6 +22,11 @@ public interface LogRepository extends JpaRepository<Log,Long>, JpaSpecification
@Query(value = "select count(*) FROM (select request_ip FROM log where create_time between ?1 and ?2 GROUP BY request_ip) as s",nativeQuery = true)
Long findIp(String date1, String date2);
/**
* findExceptionById
* @param id
* @return
*/
@Query(value = "select exception_detail FROM log where id = ?1",nativeQuery = true)
String findExceptionById(Long id);
}
......@@ -30,6 +30,8 @@ public interface LogService {
/**
* 新增日志
* @param username
* @param ip
* @param joinPoint
* @param log
*/
......
......@@ -16,4 +16,7 @@ public class LogQueryCriteria {
@Query
private String logType;
@Query(type = Query.Type.INNER_LIKE)
private String description;
}
......@@ -42,7 +42,7 @@ public class LogServiceImpl implements LogService {
@Override
public Object queryAll(LogQueryCriteria criteria, Pageable pageable){
Page<Log> page = logRepository.findAll(((root, criteriaQuery, cb) -> QueryHelp.getPredicate(root, criteria, cb)),pageable);
if (criteria.getLogType().equals("ERROR")) {
if ("ERROR".equals(criteria.getLogType())) {
return PageUtil.toPage(page.map(logErrorMapper::toDto));
}
return page;
......
......@@ -25,7 +25,7 @@ public class RedisServiceImpl implements RedisService {
@Override
public Page<RedisVo> findByKey(String key, Pageable pageable){
List<RedisVo> redisVos = new ArrayList<>();
if(!key.equals("*")){
if(!"*".equals(key)){
key = "*" + key + "*";
}
for (Object s : redisTemplate.keys(key)) {
......
......@@ -40,6 +40,7 @@ public class QuartzJobServiceImpl implements QuartzJobService {
return PageUtil.toPage(quartzJobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable));
}
@Override
public Object queryAllLog(JobQueryCriteria criteria, Pageable pageable){
return PageUtil.toPage(quartzLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable));
}
......
......@@ -9,6 +9,7 @@ import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Objects;
import java.util.Set;
/**
......@@ -61,4 +62,17 @@ public class Menu implements Serializable {
private Timestamp createTime;
public interface Update{}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Menu menu = (Menu) o;
return Objects.equals(id, menu.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
......@@ -15,6 +15,11 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author Zheng Jie
* @date 2019-04-10
......@@ -32,9 +37,23 @@ public class DictDetailController {
@GetMapping(value = "/dictDetail")
public ResponseEntity getDictDetails(DictDetailQueryCriteria criteria,
@PageableDefault(value = 10, sort = {"sort"}, direction = Sort.Direction.ASC) Pageable pageable){
String[] names = criteria.getDictName().split(",");
return new ResponseEntity(dictDetailService.queryAll(criteria,pageable),HttpStatus.OK);
}
@Log("查询多个字典详情")
@GetMapping(value = "/dictDetail/map")
public ResponseEntity getDictDetailMaps(DictDetailQueryCriteria criteria,
@PageableDefault(value = 10, sort = {"sort"}, direction = Sort.Direction.ASC) Pageable pageable){
String[] names = criteria.getDictName().split(",");
Map map = new HashMap(names.length);
for (String name : names) {
criteria.setDictName(name);
map.put(name,dictDetailService.queryAll(criteria,pageable).get("content"));
}
return new ResponseEntity(map,HttpStatus.OK);
}
@Log("新增字典详情")
@PostMapping(value = "/dictDetail")
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_CREATE')")
......
......@@ -121,22 +121,6 @@ public class UserController {
return new ResponseEntity(HttpStatus.OK);
}
/**
* 验证密码
* @param user
* @return
*/
@PostMapping(value = "/users/validPass")
public ResponseEntity validPass(@RequestBody User user){
UserDetails userDetails = SecurityUtils.getUserDetails();
Map map = new HashMap();
map.put("status",200);
if(!userDetails.getPassword().equals(EncryptUtils.encryptPassword(user.getPassword()))){
map.put("status",400);
}
return new ResponseEntity(map,HttpStatus.OK);
}
/**
* 修改密码
* @param user
......@@ -145,6 +129,9 @@ public class UserController {
@PostMapping(value = "/users/updatePass")
public ResponseEntity updatePass(@RequestBody User user){
UserDetails userDetails = SecurityUtils.getUserDetails();
if(!userDetails.getPassword().equals(EncryptUtils.encryptPassword(user.getPassword()))){
throw new BadRequestException("修改失败,旧密码错误");
}
if(userDetails.getPassword().equals(EncryptUtils.encryptPassword(user.getPassword()))){
throw new BadRequestException("新密码不能与旧密码相同");
}
......
......@@ -8,6 +8,8 @@ import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import java.util.Map;
/**
* @author Zheng Jie
* @date 2019-04-10
......@@ -46,5 +48,5 @@ public interface DictDetailService {
void delete(Long id);
@Cacheable(keyGenerator = "keyGenerator")
Object queryAll(DictDetailQueryCriteria criteria, Pageable pageable);
Map queryAll(DictDetailQueryCriteria criteria, Pageable pageable);
}
\ No newline at end of file
......@@ -26,9 +26,4 @@ public class DictDetailDTO implements Serializable {
* 排序
*/
private String sort;
/**
* 字典id
*/
private String dictName;
}
\ No newline at end of file
......@@ -15,6 +15,8 @@ import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Map;
import java.util.Optional;
/**
......@@ -32,7 +34,7 @@ public class DictDetailServiceImpl implements DictDetailService {
private DictDetailMapper dictDetailMapper;
@Override
public Object queryAll(DictDetailQueryCriteria criteria, Pageable pageable) {
public Map queryAll(DictDetailQueryCriteria criteria, Pageable pageable) {
Page<DictDetail> page = dictDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPage(page.map(dictDetailMapper::toDto));
}
......
......@@ -11,12 +11,13 @@ 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.*;
/**
* @author ${author}
* @date ${date}
*/
@Api(tags = "${className}管理")
@RestController
@RequestMapping("api")
public class ${className}Controller {
......@@ -25,6 +26,7 @@ public class ${className}Controller {
private ${className}Service ${changeClassName}Service;
@Log("查询${className}")
@ApiOperation(value = "查询${className}")
@GetMapping(value = "/${changeClassName}")
@PreAuthorize("hasAnyRole('ADMIN','${upperCaseClassName}_ALL','${upperCaseClassName}_SELECT')")
public ResponseEntity get${className}s(${className}QueryCriteria criteria, Pageable pageable){
......@@ -32,6 +34,7 @@ public class ${className}Controller {
}
@Log("新增${className}")
@ApiOperation(value = "新增${className}")
@PostMapping(value = "/${changeClassName}")
@PreAuthorize("hasAnyRole('ADMIN','${upperCaseClassName}_ALL','${upperCaseClassName}_CREATE')")
public ResponseEntity create(@Validated @RequestBody ${className} resources){
......@@ -39,6 +42,7 @@ public class ${className}Controller {
}
@Log("修改${className}")
@ApiOperation(value = "修改${className}")
@PutMapping(value = "/${changeClassName}")
@PreAuthorize("hasAnyRole('ADMIN','${upperCaseClassName}_ALL','${upperCaseClassName}_EDIT')")
public ResponseEntity update(@Validated @RequestBody ${className} resources){
......@@ -47,6 +51,7 @@ public class ${className}Controller {
}
@Log("删除${className}")
@ApiOperation(value = "删除${className}")
@DeleteMapping(value = "/${changeClassName}/{${pkChangeColName}}")
@PreAuthorize("hasAnyRole('ADMIN','${upperCaseClassName}_ALL','${upperCaseClassName}_DELETE')")
public ResponseEntity delete(@PathVariable ${pkColumnType} ${pkChangeColName}){
......
package ${package}.domain;
import lombok.Data;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import javax.persistence.*;
<#if hasTimestamp>
import java.sql.Timestamp;
......@@ -34,4 +36,8 @@ public class ${className} implements Serializable {
private ${column.columnType} ${column.changeColumnName};
</#list>
</#if>
public void copy(${className} source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment