Skip to content

Commit

Permalink
优化代码生成器,优化角色级别配置
Browse files Browse the repository at this point in the history
  • Loading branch information
elunez committed Dec 22, 2019
1 parent 5f41318 commit 4e0deae
Show file tree
Hide file tree
Showing 11 changed files with 160 additions and 148 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import me.zhengjie.domain.GenConfig;
import me.zhengjie.repository.GenConfigRepository;
import me.zhengjie.service.GenConfigService;
import me.zhengjie.utils.StringUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
Expand Down Expand Up @@ -36,25 +37,27 @@ public GenConfig find(String tableName) {
@Override
@CachePut(key = "#p0")
public GenConfig update(String tableName, GenConfig genConfig) {
// 自动设置Api路径,注释掉前需要同步取消前端的注释
String separator = File.separator;
String[] paths;
String symbol = "\\";
if (symbol.equals(separator)) {
paths = genConfig.getPath().split("\\\\");
} else {
paths = genConfig.getPath().split(File.separator);
}
StringBuilder api = new StringBuilder();
for (String path : paths) {
api.append(path);
api.append(separator);
if ("src".equals(path)) {
api.append("api");
break;
// 如果 api 路径为空,则自动生成路径
if(StringUtils.isBlank(genConfig.getApiPath())){
String separator = File.separator;
String[] paths;
String symbol = "\\";
if (symbol.equals(separator)) {
paths = genConfig.getPath().split("\\\\");
} else {
paths = genConfig.getPath().split(File.separator);
}
StringBuilder api = new StringBuilder();
for (String path : paths) {
api.append(path);
api.append(separator);
if ("src".equals(path)) {
api.append("api");
break;
}
}
genConfig.setApiPath(api.toString());
}
genConfig.setApiPath(api.toString());
return genConfigRepository.save(genConfig);
}
}
17 changes: 15 additions & 2 deletions eladmin-system/src/main/java/me/zhengjie/AppRun.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
package me.zhengjie;

import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.utils.SpringContextHolder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @author Zheng Jie
* @date 2018/11/15 9:20:19
*/
@EnableAsync
@RestController
@SpringBootApplication
@EnableTransactionManagement
public class AppRun {
Expand All @@ -31,7 +34,17 @@ public SpringContextHolder springContextHolder() {
@Bean
public ServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory fa = new TomcatServletWebServerFactory();
fa.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> connector.setProperty("relaxedQueryChars", "[]{}"));
fa.addConnectorCustomizers(connector -> connector.setProperty("relaxedQueryChars", "[]{}"));
return fa;
}

/**
* 访问首页提示
* @return /
*/
@GetMapping("/")
@AnonymousAccess
public String index() {
return "Backend service started successfully";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,11 @@ public interface RoleRepository extends JpaRepository<Role, Long>, JpaSpecificat
@Modifying
@Query(value = "delete from roles_menus where menu_id = ?1",nativeQuery = true)
void untiedMenu(Long id);

/**
* 根据角色权限查询
* @param permission /
* @return /
*/
Role findByPermission(String permission);
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.RoleDto;
import me.zhengjie.modules.system.service.dto.RoleQueryCriteria;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.UserDto;
Expand All @@ -21,7 +22,6 @@
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
Expand Down Expand Up @@ -81,9 +81,7 @@ public ResponseEntity<Object> getRoles(RoleQueryCriteria criteria, Pageable page
@ApiOperation("获取用户级别")
@GetMapping(value = "/level")
public ResponseEntity<Object> getLevel(){
UserDto user = userService.findByName(SecurityUtils.getUsername());
List<Integer> levels = roleService.findByUsersId(user.getId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
return new ResponseEntity<>(Dict.create().set("level", Collections.min(levels)),HttpStatus.OK);
return new ResponseEntity<>(Dict.create().set("level", getLevels(null)),HttpStatus.OK);
}

@Log("新增角色")
Expand All @@ -94,6 +92,7 @@ public ResponseEntity<Object> create(@Validated @RequestBody Role resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
getLevels(resources.getLevel());
return new ResponseEntity<>(roleService.create(resources),HttpStatus.CREATED);
}

Expand All @@ -102,6 +101,7 @@ public ResponseEntity<Object> create(@Validated @RequestBody Role resources){
@PutMapping
@PreAuthorize("@el.check('roles:edit')")
public ResponseEntity<Object> update(@Validated(Role.Update.class) @RequestBody Role resources){
getLevels(resources.getLevel());
roleService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
Expand All @@ -111,7 +111,9 @@ public ResponseEntity<Object> update(@Validated(Role.Update.class) @RequestBody
@PutMapping(value = "/menu")
@PreAuthorize("@el.check('roles:edit')")
public ResponseEntity<Object> updateMenu(@RequestBody Role resources){
roleService.updateMenu(resources,roleService.findById(resources.getId()));
RoleDto role = roleService.findById(resources.getId());
getLevels(role.getLevel());
roleService.updateMenu(resources,role);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

Expand All @@ -120,7 +122,31 @@ public ResponseEntity<Object> updateMenu(@RequestBody Role resources){
@DeleteMapping
@PreAuthorize("@el.check('roles:del')")
public ResponseEntity<Object> delete(@RequestBody Set<Long> ids){
roleService.delete(ids);
for (Long id : ids) {
RoleDto role = roleService.findById(id);
getLevels(role.getLevel());
}
try {
roleService.delete(ids);
} catch (Throwable e){
ThrowableUtil.throwForeignKeyException(e, "所选角色存在用户关联,请取消关联后再试");
}
return new ResponseEntity<>(HttpStatus.OK);
}

/**
* 获取用户的角色级别
* @return /
*/
private int getLevels(Integer level){
UserDto user = userService.findByName(SecurityUtils.getUsername());
List<Integer> levels = roleService.findByUsersId(user.getId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
int min = Collections.min(levels);
if(level != null){
if(level < min){
throw new BadRequestException("权限不足,你的角色级别:" + min + ",低于操作的角色级别:" + level);
}
}
return min;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,16 @@ public void update(Role resources) {
if(role1 != null && !role1.getId().equals(role.getId())){
throw new EntityExistException(Role.class,"username",resources.getName());
}

role1 = roleRepository.findByPermission(resources.getPermission());
if(role1 != null && !role1.getId().equals(role.getId())){
throw new EntityExistException(Role.class,"permission",resources.getPermission());
}
role.setName(resources.getName());
role.setRemark(resources.getRemark());
role.setDataScope(resources.getDataScope());
role.setDepts(resources.getDepts());
role.setLevel(resources.getLevel());
role.setPermission(resources.getPermission());
roleRepository.save(role);
}

Expand All @@ -127,11 +131,7 @@ public void untiedMenu(Long id) {
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
for (Long id : ids) {
try {
roleRepository.deleteById(id);
}catch (Throwable e){
ThrowableUtil.throwForeignKeyException(e, "该角色存在用户关联,请取消关联后再试");
}
roleRepository.deleteById(id);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,9 @@ public class ${className}Controller {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

@DeleteMapping(value = "/{${pkChangeColName}}")
@Log("删除${apiAlias}")
@ApiOperation("删除${apiAlias}")
@PreAuthorize("@el.check('${changeClassName}:del')")
public ResponseEntity<Object> delete(@PathVariable ${pkColumnType} ${pkChangeColName}){
${changeClassName}Service.delete(${pkChangeColName});
return new ResponseEntity<>(HttpStatus.OK);
}

@Log("多选删除${apiAlias}")
@ApiOperation("多选删除${apiAlias}")
@PreAuthorize("@el.check('${changeClassName}:del')")
@DeleteMapping
public ResponseEntity<Object> deleteAll(@RequestBody ${pkColumnType}[] ids) {
${changeClassName}Service.deleteAll(ids);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ public class ${className}QueryCriteria{
@Query(type = Query.Type.NOT_EQUAL)
private ${column.columnType} ${column.changeColumnName};
</#if>
<#if column.queryType = 'NotNull'>
/** 不为空 */
@Query(type = Query.Type.NOT_NULL)
private ${column.columnType} ${column.changeColumnName};
</#if>
<#if column.queryType = '>='>
/** 大于等于 */
@Query(type = Query.Type.GREATER_THAN)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,6 @@ public interface ${className}Service {
*/
void update(${className} resources);

/**
* 删除
* @param ${pkChangeColName} /
*/
void delete(${pkColumnType} ${pkChangeColName});

/**
* 多选删除
* @param ids /
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ import cn.hutool.core.util.IdUtil;
<#if !auto && pkColumnType = 'String'>
import cn.hutool.core.util.IdUtil;
</#if>
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
// 默认不使用缓存
//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;
Expand All @@ -46,7 +47,7 @@ import java.util.LinkedHashMap;
* @date ${date}
*/
@Service
@CacheConfig(cacheNames = "${changeClassName}")
//@CacheConfig(cacheNames = "${changeClassName}")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ${className}ServiceImpl implements ${className}Service {

Expand All @@ -60,28 +61,28 @@ public class ${className}ServiceImpl implements ${className}Service {
}

@Override
@Cacheable
//@Cacheable
public Map<String,Object> queryAll(${className}QueryCriteria criteria, Pageable pageable){
Page<${className}> page = ${changeClassName}Repository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPage(page.map(${changeClassName}Mapper::toDto));
}

@Override
@Cacheable
//@Cacheable
public List<${className}Dto> queryAll(${className}QueryCriteria criteria){
return ${changeClassName}Mapper.toDto(${changeClassName}Repository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
}

@Override
@Cacheable(key = "#p0")
//@Cacheable(key = "#p0")
public ${className}Dto findById(${pkColumnType} ${pkChangeColName}) {
${className} ${changeClassName} = ${changeClassName}Repository.findById(${pkChangeColName}).orElseGet(${className}::new);
ValidationUtil.isNull(${changeClassName}.get${pkCapitalColName}(),"${className}","${pkChangeColName}",${pkChangeColName});
return ${changeClassName}Mapper.toDto(${changeClassName});
}

@Override
@CacheEvict(allEntries = true)
//@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public ${className}Dto create(${className} resources) {
<#if !auto && pkColumnType = 'Long'>
Expand All @@ -104,7 +105,7 @@ public class ${className}ServiceImpl implements ${className}Service {
}

@Override
@CacheEvict(allEntries = true)
//@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public void update(${className} resources) {
${className} ${changeClassName} = ${changeClassName}Repository.findById(resources.get${pkCapitalColName}()).orElseGet(${className}::new);
Expand All @@ -127,14 +128,7 @@ public class ${className}ServiceImpl implements ${className}Service {
}

@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public void delete(${pkColumnType} ${pkChangeColName}) {
${changeClassName}Repository.deleteById(${pkChangeColName});
}

@Override
@CacheEvict(allEntries = true)
//@CacheEvict(allEntries = true)
public void deleteAll(${pkColumnType}[] ids) {
for (${pkColumnType} id : ids) {
${changeClassName}Repository.deleteById(${pkChangeColName});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,7 @@ export function add(data) {
})
}

export function del(${pkChangeColName}) {
return request({
url: 'api/${changeClassName}/' + ${pkChangeColName},
method: 'delete'
})
}
export function delAll(ids) {
export function del(ids) {
return request({
url: 'api/${changeClassName}/',
method: 'delete',
Expand All @@ -30,4 +24,4 @@ export function edit(data) {
})
}

export default { add, edit, del, delAll }
export default { add, edit, del }
Loading

0 comments on commit 4e0deae

Please sign in to comment.