我正在应用类似于 Spring Data JPA 的存储库,其中我只会创建实体存储库的接口(interface):
public interface AuthorRepository extends Repository<Author, Long> {
}
我还有这个存储库接口(interface):
public interface Repository <T, ID extends Serializable> {
List<T> findAll() throws Exception;
}
及其实现,我发现很难将类名作为参数化 (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();
}
}
}
我找不到如何动态生成要作为 NamedQuery 字符串的一部分和 参数创建的实体类(例如 Author)的方法em.createNamequery().
感谢您的帮助。
最佳答案
在 RepositoryImpl 中,您可以像这样注入(inject)实体信息:
@Autowired
private JpaEntityInformation<T, ID> entityInformation;
然后使用它,例如:
String entityName = entityInformation.getEntityName();
Class<T> entityType = entityInformation.getJavaType();
遗憾的是,自定义 RepositoryFragments 无法 Autowiring JpaEntityInformation,因为它们是单例,因此对于通用片段,需要在每个方法调用中传递实体类并使用 JpaEntityInformationSupport.getEntityInformation(clazz,EntityManager)
或者修改片段的BeanDefinition并使用注入(inject)点获取clazz。
关于java - 在JPA和存储库接口(interface)中获取实体类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46377483/