【问题标题】:Getting a JPA Criteria Query to work with an inherited list让 JPA 标准查询与继承的列表一起使用
【发布时间】: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&lt;Test,Subject&gt;)。直觉上感觉这应该是解决方案,但继承还远远不够。如果我在查询中省略元模型引用并将其替换为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


    【解决方案1】:

    在 JPQL 中(我真的建议你在不需要动态生成的查询时使用它),你可以这样写:

    select e from Exam e
    inner join e.students student
    where student.id = :studentId
    

    如果您真的想使用 Criteria API 来编写此查询,请执行相同的操作:创建一个连接并检查连接实体的 ID 是否等于给定的学生 ID。它应该是这样的:

    Join<Exam, Student> studentJoin = root.join(Exam_.students);
    cq.where(qb.equal(studentJoin.get(Student_.id), student.getId());
    

    【讨论】:

    • 感谢您的输入 - 您的代码从数据库中生成了 0 个结果,这些查询应该提供少量的查询,因此在我将其标记为正确之前,我将尝试更多地使用连接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2014-10-26
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    相关资源
    最近更新 更多