【发布时间】:2018-12-14 13:22:46
【问题描述】:
我不确定是否可能,但我的问题是:有没有办法在基本存储库实现中获取泛型参数的类名。 这是我的基本界面:
@NoRepositoryBean
public interface AclBaseRepository<T extends BaseEntity> extends QuerydslPredicateExecutor<T>, CrudRepository<T, Long> {
List<T> findAllWithAcl(Predicate predicate);
Page<T> findAllWithAcl(Predicate predicate, Pageable pageable);
}
这是我的实现
@NoRepositoryBean
public class AclBaseRepositoryImpl<T extends BaseEntity> extends QuerydslJpaRepository<T, Long> implements AclBaseRepository<T> {
@SuppressWarnings("unchecked")
public AclBaseRepositoryImpl(JpaEntityInformation<T, Long> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
}
@Override
public List<T> findAllWithAcl(Predicate predicate) {
return findAll(predicate);
}
@Override
public Page<T> findAllWithAcl(Predicate predicate, Pageable pageable) {
return findAll(predicate, pageable);
}
}
示例用法:
public interface AccountRepository extends AclBaseRepository<Account> {
}
基本思想是:为所有“已实现”的存储库建立一个公共基础存储库,并使用一些新方法(例如 findAllWithAcl)。这些新方法将在定义的查询谓词中注入一个附加谓词(QueryDsl),该谓词基本上根据某些 ACL 表过滤行。对于该查询,我需要正在加载的实体的类名。我可以将类名作为参数传递给构造函数,但是由于我将此基础存储库用作新的 repositoryBaseClass(例如@EnableJpaRepositories(repositoryBaseClass = AclBaseRepositoryImpl.class))并且我的存储库是接口,因此我无法控制参数。
这可能吗?是否有另一种/更好的方法可以做到这一点而无需多次重复相同的代码?
【问题讨论】:
标签: java spring generics spring-data-jpa