使用给定的 属性 集合的 Hibernate select 个元素

Hibernate select elements of collection with a given property

实体 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"

但什么也没有。

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

p.contributors.id

您正在尝试访问 p.contributorsid,这是 List<User>。列表没有 ID。所以那是行不通的。

select p.contributors

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

在 SQL 你会怎么做?随着加入。与 JPQL 相同:

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

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

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

Id 是此集合的元素的属性。

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

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