【发布时间】:2013-02-20 22:53:06
【问题描述】:
假设我有一个实体
@Entity
public class Test {
@ManyToMany
@JoinTable(..etc..)
private List<Subject> subjects; // School subjects this test is associated with
....
还有一个实体
@Entity
public class Exam extends Test {
// Inherits subjects from test
// Does some things specific to exams
...
我想编写一个条件查询(带有元模型),它只给我与某个Subject 关联的Exams。我的问题是:我该如何编写这个查询?
我尝试过的如下:
如果我写
CriteriaBuilder cb = em.getCriteriaBuilder(); // em is the EntityManager
CriteriaQuery<Exam> cq = cb.createQuery(Exam.class);
Root<Exam> root = cq.from(Exam.class);
cq.where(cb.isMember(subject, root.get(Exam_.subjects)));
return em.createQuery(cq);
编译器不会编译它,说error: no suitable method found for get(ListAttribute<Test,Subject>)。直觉上感觉这应该是解决方案,但继承还远远不够。如果我在查询中省略元模型引用并将其替换为root.get("subjects"),它也将不起作用。
如果我写
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Exam> cq = cb.createQuery(Exam.class);
Root<Test> root = cq.from(Test.class);
cq.where(cb.isMember(subject, root.get(Exam_.subjects)));
return em.createQuery(cq);
这感觉不对,但它确实可以编译。然而,在实际执行代码时,我遇到了一个异常:IllegalStateException: No explicit selection and an implicit one could not be determined,我将其解释为在Root 的类型之间进行混杂的结果。尝试root.get(Test_.subjects) 会产生相同的结果。
我使用 Hibernate 作为我的 JPA 实现,但我尝试坚持使用 JPA Criteria Queries。
【问题讨论】:
标签: hibernate jpa jpa-2.0 criteria-api