Java 获取泛型基本存储库的参数类型名称
我甚至不确定是否可能,但我的问题是:是否有一种方法可以在基本存储库实现中获取泛型参数的类名。 这是我的基本界面:Java 获取泛型基本存储库的参数类型名称,java,spring,generics,spring-data-jpa,Java,Spring,Generics,Spring Data Jpa,我甚至不确定是否可能,但我的问题是:是否有一种方法可以在基本存储库实现中获取泛型参数的类名。 这是我的基本界面: @NoRepositoryBean public interface AclBaseRepository<T extends BaseEntity> extends QuerydslPredicateExecutor<T>, CrudRepository<T, Long> { List<T> findAllWithAcl(Pre
@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
公共接口AclBaseRepository扩展了QuerydslPredicateExecutor,CrudRepository{
列表findAllWithAcl(谓词);
PageFindAllWithACL(谓词谓词,可分页,可分页);
}
这是我的实现
@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);
}
}
@NoRepositoryBean
公共类AclBaseRepositoryImpl扩展了QuerydslJpaRepository实现了AclBaseRepository{
@抑制警告(“未选中”)
公共AclBaseRepositoryImpl(JPAEEntityInformation entityInformation,EntityManager EntityManager){
超级(实体信息、实体管理器);
}
@凌驾
公共列表findAllWithAcl(谓词){
返回findAll(谓词);
}
@凌驾
公共页findAllWithAcl(谓词谓词,可分页,可分页){
返回findAll(谓词,可分页);
}
}
用法示例:
public interface AccountRepository extends AclBaseRepository<Account> {
}
公共接口AccountRepository扩展了AclBaseRepository{
}
其基本思想是:使用一些新方法(例如findAllWithAcl)为所有“已实现”的存储库建立一个公共的基础存储库。这些新方法将向已定义的查询谓词中注入一个附加谓词(QueryDsl),该谓词基本上根据一些ACL表过滤行。对于该查询,我需要加载的实体的类名。我可以将类名作为参数传递给构造函数,但由于我将此基本存储库用作新的repositoryBaseClass(例如@EnableJpaRepositories(repositoryBaseClass=AclBaseRepositoryImpl.class)
),并且我的存储库是接口,因此我无法控制参数。
这可能吗?是否有另一种/更好的方法可以做到这一点,而无需多次重复相同的代码?您可以从构造函数中提供的
JpaEntityInformation
实例中获取信息。
因为它实现了,并且您可以通过getEntityName()
访问实体名称,也可以通过getJavaType()
访问域类
另外,由于
AclBaseRepositoryImpl
inherits从中继承,您只需调用getDomainClass
谢谢。好简单!