Skip to content

Commit

Permalink
代码生成器优化,新增多数据字典支持,用户修改密码优化
Browse files Browse the repository at this point in the history
  • Loading branch information
elunez committed Jun 29, 2019
1 parent 375cdf4 commit c4fc3da
Show file tree
Hide file tree
Showing 32 changed files with 183 additions and 195 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
Join join() default Join.LEFT;

enum Type {
/** jie 2019/6/4 相等 */
EQUAL
/** Dong ZhaoYang 2017/8/7 大于等于 */
, GREATER_THAN
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,9 @@ public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuild
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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,15 @@ public class TableInfo {

/** 创建日期 **/
private Object createTime;

// 数据库引擎
private Object engine;

// 编码集
private Object coding;

// 备注
private Object remark;


}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public interface GenConfigService {
/**
* update
* @param genConfig
* @return
*/
@CacheEvict(allEntries = true)
GenConfig update(GenConfig genConfig);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
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;
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;
Expand All @@ -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();
Expand All @@ -50,12 +49,11 @@ public Object getTables(String name, int[] startEnd) {

@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) {
Expand Down
16 changes: 3 additions & 13 deletions eladmin-generator/src/main/java/me/zhengjie/utils/GenUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@ public static List<String> getFrontTemplateNames() {
List<String> templateNames = new ArrayList<>();
templateNames.add("api");
templateNames.add("index");
templateNames.add("header");
templateNames.add("edit");
templateNames.add("eForm");
return templateNames;
}
Expand Down Expand Up @@ -174,8 +172,8 @@ public static void generatorCode(List<ColumnInfo> columnInfos, GenConfig genConf
* 定义后端文件路径以及名称
*/
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;
}
Expand Down Expand Up @@ -229,16 +227,8 @@ public static String getFrontFilePath(String templateName, GenConfig genConfig,
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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ public interface LogService {

/**
* 新增日志
* @param username
* @param ip
* @param joinPoint
* @param log
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,7 @@ public class LogQueryCriteria {

@Query
private String logType;

@Query(type = Query.Type.INNER_LIKE)
private String description;
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public Object queryAll(JobQueryCriteria criteria, Pageable pageable){
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));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Objects;
import java.util.Set;

/**
Expand Down Expand Up @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
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
Expand All @@ -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')")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,22 +121,6 @@ public ResponseEntity delete(@PathVariable Long id){
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
Expand All @@ -145,6 +129,9 @@ public ResponseEntity validPass(@RequestBody User user){
@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("新密码不能与旧密码相同");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;

import java.util.Map;

/**
* @author Zheng Jie
* @date 2019-04-10
Expand Down Expand Up @@ -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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,4 @@ public class DictDetailDTO implements Serializable {
* 排序
*/
private String sort;

/**
* 字典id
*/
private String dictName;
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
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;

/**
Expand All @@ -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));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -25,20 +26,23 @@ 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){
return new ResponseEntity(${changeClassName}Service.queryAll(criteria,pageable),HttpStatus.OK);
}

@Log("新增${className}")
@ApiOperation(value = "新增${className}")
@PostMapping(value = "/${changeClassName}")
@PreAuthorize("hasAnyRole('ADMIN','${upperCaseClassName}_ALL','${upperCaseClassName}_CREATE')")
public ResponseEntity create(@Validated @RequestBody ${className} resources){
return new ResponseEntity(${changeClassName}Service.create(resources),HttpStatus.CREATED);
}

@Log("修改${className}")
@ApiOperation(value = "修改${className}")
@PutMapping(value = "/${changeClassName}")
@PreAuthorize("hasAnyRole('ADMIN','${upperCaseClassName}_ALL','${upperCaseClassName}_EDIT')")
public ResponseEntity update(@Validated @RequestBody ${className} resources){
Expand All @@ -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}){
Expand Down
Loading

0 comments on commit c4fc3da

Please sign in to comment.