在 JPA 和存储库接口中获取实体 Class

Getting Entity Class in JPA and Repository Interface

我正在应用类似于 Spring Data JPA 的存储库,我将只创建一个实体存储库的接口:

public interface AuthorRepository extends Repository<Author, Long> {
}

我也有这个 Repository 接口:

public interface Repository <T, ID extends Serializable> {
    List<T> findAll() throws Exception;
}

及其实现,我发现很难将 class 名称作为参数化 (T) 传递给存储库:

public class RepositoryImpl implements Repository {
    @Inject
    private EntityManager em;

    @Override
    public List<Object> findAll() throws Exception {
        try {
            String namedQuery = "SELECT a FROM " + <How do I get the entity here as Author?> + " a";
            TypedQuery<Object> query = em.createNamedQuery(namedQuery, <How do I get the entity class as Author.class?>);

            return query.getResultList();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new ApplicationException();
        }
    }

}

我找不到如何动态生成实体 class(例如 Author)作为 NamedQuery[ 的一部分创建的方法=29=] 字符串和 em.createNamequery().

的参数

感谢您的帮助。

搜索万维网给了我类似的方法和代码,但 none 有效,但 TypeTools 非常有效。

在 RepositoryImpl 中,您可以像这样注入实体信息:

@Autowired
private JpaEntityInformation<T, ID> entityInformation;

然后使用它,例如:

String entityName = entityInformation.getEntityName();

Class<T> entityType = entityInformation.getJavaType();

Custom RepositoryFragments 很遗憾不能自动装配 JpaEntityInformation,因为它们是单例,因此对于通用片段,需要在每个方法调用中传递实体 class 并使用 JpaEntityInformationSupport.getEntityInformation(clazz, entityManager) 或修改片段的 BeanDefinition 并使用注入点获取 clazz。