java - 获取通用基础存储库的参数类型名称

标签 java spring generics spring-data-jpa

我不确定是否可能,但我的问题是:有没有办法在基本存储库实现中获取通用参数的类名。 这是我的基本界面:

@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 实例获取信息。 由于它实现了 JpaEntityMetadataEntityMetadata您可以通过 getEntityName() 访问实体名称,并通过 getJavaType() 访问域类。

此外,由于 AclBaseRepositoryImpl 继承自 QuerydslJpaRepository它继承自 SimpleJpaRepository您只需调用getDomainClass即可。

关于java - 获取通用基础存储库的参数类型名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53780612/

相关文章:

java - removeMouseListener 方法不起作用

java - Spring boot自定义注解..看看它用在哪里

java - Selenium WebDriver java.lang.UnsupportedClassVersionError : org/openqa/selenium/WebDriver : Unsupported major. 次要版本 52.0

java - Spring 日期转换休息一天

java - 可比较无法转换为 T#1

java - 在 Linux 中运行小程序?

java - Spring boot中 Autowiring 接口(interface)错误

java - 为什么我不能在 Spring Boot 中使用它的 UserRepository 保存我的 @Entity User

java - 关于泛型、有界通配符和 getClass() 的棘手面试问题

c# - 在 C# 中重写泛型方法