Hibernate选择具有给定属性的collection元素 [英] Hibernate select elements of collection with a given property

查看:45
本文介绍了Hibernate选择具有给定属性的collection元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实体 Project 具有集合属性 contributors ,该属性通过 @OneToMany 关系映射到实体 User

Entity Project has a collection property contributors mapped with a @OneToMany relationship to entity User

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

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

    ...
}

然后,我需要在添加之前检查 contributors 是否已经具有 id contributorId user .我正在尝试使用HQL查询,但显然我没有任何经验.

I then need to check if contributors already has a user with id contributorId before adding it. I am trying with HQL query, but I am clearly quite innept.

我正在尝试:

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]

有没有一个好的撒玛利亚人想给我一点推动力?

Is there a good samaritan that would like to give me a little push?

我尝试的另一种方法是

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

但什么都没有.

推荐答案

贡献者是一个集合.因此,它没有名为id的属性.

contributors is a Collection. As such, it does not have an attribute named id.

Id是此Collection元素的属性.

Id is an attribute of the elements of this Collection.

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

You can fix the issue by joining the collection instead of dereferencing it:

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

这篇关于Hibernate选择具有给定属性的collection元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆