【问题标题】:Hibernate select elements of collection with a given property休眠选择具有给定属性的集合元素
【发布时间】:2016-10-10 14:11:51
【问题描述】:

实体 Project 有一个集合属性 contributors 映射到实体 User@OneToMany 关系

@Entity
@Table( name = "projects" )
public class Project {
    ...

    @OneToMany
    @JoinTable(name = "project_contributors")
    private List<User> contributors = new ArrayList<User>();

    ...
}

然后我需要在添加之前检查contributors 是否已经有userid contributorId。我正在尝试使用 HQL 查询,但我显然很无能。

我正在尝试什么:

Query query = session.createQuery(
        "select p.contributors from Project p where p.id = :pId and p.contributors.id = :cId"
    );

query.setParameter("pId", projectId);
query.setParameter("cId", contributorId);

@SuppressWarnings("unchecked")
List<User> res = (List<User>) query.list();

但它给出了错误

illegal attempt to dereference collection [project0_.id.contributors] with element property reference [id]

有好心人愿意给我一点推动力吗?

我的另一个尝试是

"select p.contributors as c from Project p where p.id = :pId and c.id = :cId"

但什么都没有。

【问题讨论】:

    标签: hibernate hql


    【解决方案1】:

    它有助于阅读您的 HQL,就像它是试图取消引用 Java 类中的字段的 Java 代码一样:

    p.contributors.id
    

    您正尝试访问p.contributorsid,即List&lt;User&gt;。列表没有 ID。所以这是行不通的。

    select p.contributors
    

    这样的查询,如果它是正确的,将返回一个贡献者列表。这也不是你想要的。

    您将如何在 SQL 中执行此操作?加入。与 JPQL 相同:

    select c from Project p
    join p.contributors c
    where p.id = :pId and c.id = :cId
    

    进行连接并为其分配别名允许查询关联的目标实体。

    【讨论】:

    • 谢谢,我已经给@Tanvi 回答了,希望没问题。有没有办法用 Hibernate Criteria 进行同样的查询?
    【解决方案2】:

    contributors 是一个集合。因此,它没有名为 id 的属性。

    Id 是此 Collection 元素的属性。

    您可以通过加入集合而不是取消引用来解决此问题:

    SELECT p 
      FROM Project pj 
      JOIN pj.contributors  p 
     WHERE pj.id       = :pId
       AND p.Id     = :cId
    

    【讨论】:

    • 坦维你太棒了!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 2011-02-25
    • 2011-10-13
    • 2010-11-02
    相关资源
    最近更新 更多