【问题标题】:Get parameter type name of generic base repository获取通用基础存储库的参数类型名称
【发布时间】: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


    【解决方案1】:

    您可以从构造函数中提供的JpaEntityInformation 实例中获取信息。 由于它实现了JpaEntityMetadataEntityMetadata,因此您可以通过getEntityName() 访问实体名称,并通过getJavaType() 访问域类。

    另外,由于AclBaseRepositoryImpl 继承自QuerydslJpaRepository,而QuerydslJpaRepository 继承自SimpleJpaRepository,您可以简单地调用getDomainClass

    【讨论】:

    • 谢谢。好简单!
    猜你喜欢
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多