我不确定是否可能,但我的问题是:有没有办法在基本存储库实现中获取通用参数的类名。 这是我的基本界面:
@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)为所有“已实现”存储库提供一个公共(public)基础存储库。这些新方法会将附加谓词 (QueryDsl) 注入(inject)到定义的查询谓词中,该谓词基本上根据某些 ACL 表过滤行。对于该查询,我需要正在加载的实体的类名。我可以将类名作为参数传递给构造函数,但由于我使用此基本存储库作为新的repositoryBaseClass(例如 @EnableJpaRepositories(repositoryBaseClass = AclBaseRepositoryImpl.class)
),并且我的存储库是接口(interface),我无法控制参数。
这可能吗?是否有另一种/更好的方法可以做到这一点,而无需多次重复相同的代码?
最佳答案
您可以从构造函数中提供的 JpaEntityInformation
实例获取信息。
由于它实现了 JpaEntityMetadata
和 EntityMetadata
您可以通过 getEntityName()
访问实体名称,并通过 getJavaType()
访问域类。
此外,由于 AclBaseRepositoryImpl
继承自 QuerydslJpaRepository
它继承自 SimpleJpaRepository
您只需调用getDomainClass
即可。
关于java - 获取通用基础存储库的参数类型名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53780612/