改写LinCMS在PermissionHandleListener改写中JPA失效
尝试用JPA改写LinCMS
在改写PermissionHandleListener的时候遇到JPA调用save无法保存到数据库的情况,
在ApplicationListener中save失效,但是可以在Controller中使用
粘贴全部相关代码,切记添加代码注释(请勿截图)
@Component
public class PermissionHandleListener implements ApplicationListener<ContextRefreshedEvent> {
private final PermissionMetaCollector permissionMetaCollector;
private final PermissionService permissionService;
private final PermissionRepository permissionRepository;
@Autowired
public PermissionHandleListener(PermissionMetaCollector permissionMetaCollector, PermissionService permissionService, PermissionRepository permissionRepository) {
this.permissionMetaCollector = permissionMetaCollector;
this.permissionService = permissionService;
this.permissionRepository = permissionRepository;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
addNewPermissions();
removeUnusedPermissions();
}
private void addNewPermissions(){
permissionMetaCollector.getMetaMap().values().forEach(meta -> {
String module = meta.getModule();
String permission = meta.getPermission();
createPermissionIfNotExist(permission, module);
});
}
private void removeUnusedPermissions(){
List<SysPermission> allPermissions = permissionRepository.findAll();
Map<String, MetaInfo> metaMap = permissionMetaCollector.getMetaMap();
for (SysPermission permission : allPermissions) {
boolean stayedInMeta = metaMap
.values()
.stream()
.anyMatch(meta -> meta.getModule().equals(permission.getModule())
&& meta.getPermission().equals(permission.getName()));
if (!stayedInMeta) {
permission.setMount(false);
permissionRepository.save(permission);
}
}
}
private void createPermissionIfNotExist(String name, String module) {
SysPermission permission;
permission = permissionService.getOneByNameAndModule(name, module);
if (permission == null) {
permission = permissionService.createByNameAndModule(name, module);
}
if (permission != null && !permission.getMount()) {
permission.setMount(true);
permission = permissionRepository.save(permission);
}
}
}
23
收起
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星