微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

拦截 Spring Data 中的存储库方法调用,即时优化查询

如何解决拦截 Spring Data 中的存储库方法调用,即时优化查询

假设我有一些扩展 CRUDRepositor 的接口。那里有像 findByField 这样的方法。其中一些方法应该只返回属于用户有权访问的一组实体的实体(group数据库中的一列,因此它是为大多数实体定义的字段)。我想通过允许在存储库方法上使用注释(如@Protected)来实现这一点,然后当调用这些方法而不是调用 findByField 时,会在幕后调用方法 findByFieldAndGroup。使用 AOP(拦截用我的 @Protected 标记注释的方法)可以在方法有效执行之前分配组。

public interface MyRepository extends CRUDRepository<MyEntity,long> {

    @Protected
    Optional<MyEntity> findById(Long id); // Should become findByIdAndGroup(Long id,String group) behind the scenes

    @Protected
    Collection<MyEntity> findAll();

}

有没有办法做到这一点?在最坏的情况下,我要么手动添加所有方法,要么完全切换到示例查询方法(您可以更轻松地动态添加组)或使用 ASM 使用 Java 代理生成方法(操作字节码)……但这些方法不太实用,需要大量重构。

编辑:找到这些相关问题Spring data jpa - modifying query before execution Spring Data JPA and spring-security: filter on database level (especially for paging) 其他相关参考资料包括 this ticket on GitHub(没有进展,只是 QueryDSL 的一种解决方案,它排除了使用基于方法名称查询)和 this thread

解决方法

您可以使用 filters(一种特定的休眠功能)来解决此问题。

想法如下。

首先,您需要使用要应用的不同过滤器对实体进行注释,在您的情况下,例如:

@Entity
//...
@Filters({
  @Filter(name="filterByGroup",condition="group_id = :group_id")
})
public class MyEntity implements Serializable { 
  // ...
}

然后,您需要访问底层 EntityManager,因为您需要与关联的 Hibernate Session 进行交互。您有几种方法可以做到这一点。例如,您可以为任务定义一个自定义事务管理器,例如:

public class FilterAwareJpaTransactionManager extends JpaTransactionManager {

  @Override
  protected EntityManager createEntityManagerForTransaction() {
    final EntityManager entityManager = super.createEntityManagerForTransaction();
    // Get access to the underlying Session object
    final Session session = entityManager.unwrap(Session.class);

    // Enable filter
    try{
      this.enableFilterByGroup(session);
    }catch (Throwable t){
      // Handle exception as you consider appropriate
      t.printStackTrace();
    }

    return entityManager;
  }

  private void enableFilterByGroup(final Session session){
    final String group = this.getGroup();

    if (group == null) {
      // Consider logging the problem
      return;
    }

    session
      .enableFilter("filterByGroup")
      .setParameter("group_id",group)
    ;
  }

  private String getGroup() {
    // You need access to the user information. For instance,in the case of Spring Security you can try:
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null) {
      return null;
    }

    // Your user type
    MyUser user = (MyUser)authentication.getPrincipal();
    String group = user.getGroup();
    return group;
  }
}

然后,在您的数据库配置中注册此 TransationManager 而不是默认的 JpaTransactionManager

@Bean
public PlatformTransactionManager transactionManager() {
  JpaTransactionManager transactionManager = new FilterAwareJpaTransactionManager();
  transactionManager.setEntityManagerFactory(entityManagerFactory());
  return transactionManager;
}

您还可以通过创建自定义 EntityManager 或在 bean 中注入 Session 来访问 JpaRepository 和关联的 @PersistenceContext,但我认为上述方法是一种更简单的方法,尽管它有总是被应用的缺点。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。