改写LinCMS在PermissionHandleListener改写中JPA失效

改写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);
    }
  }
}

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
7七月 2020-11-20 11:37:16

这样的问题,不可能就看这个截图和代码就能解决的。既然自己要改写,那就多研究下

  • 提问者 IceDream1024 #1
    JPA 在ContextRefreshedEvent里面save好像无解,现在JPA和Mybatis混用,ContextRefreshedEvent这里只能用Mybatis?‍♀️
    2020-11-20 16:14:59
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师