0

我有以下课程:

@Entity
@Table(name = "entity")
    public class Entity extends Model
    {
       @ManyToMany(fetch = FetchType.EAGER)
       @JoinTable(name = "entity_owner", joinColumns = @JoinColumn(name = "entity_id"), inverseJoinColumns = @JoinColumn(name = "user_id"))
       private Set<UserAccount> owners;

       @ManyToMany(fetch = FetchType.EAGER)
       @JoinTable(name = "entity_assignee", joinColumns = @JoinColumn(name = "entity_id"), inverseJoinColumns = @JoinColumn(name = "user_id"))
       private Set<UserAccount> assignees;
    }

我有一个用户帐户,我希望能够返回在所有者或受让人中拥有用户的所有实体对象。

我试过这个,它几乎可以工作,但似乎回到了某种笛卡尔结果:

String query = "SELECT r FROM models.Entity r LEFT JOIN r.assignees a LEFT JOIN r.owners n ";
query += "WHERE a.id = 1 OR n.id = 1";

谁能告诉我我做错了什么?

4

2 回答 2

0

当已经有 UserAccount 实例可用于过滤结果时, 可以使用MEMBER OF表达式:

SELECT DISTINCT(e) 
FROM SomeEntity e 
WHERE :someUser MEMBER OF e.assignees OR 
      :someUser MEMBER OF e.owners

UserAccount ua ...
em.createQuery(jpql).setParameter("someUser", ua)

如果由于某种原因首选类似于原始查询的查询,则添加 DISTINCT 就足够了。

于 2013-05-31T04:42:40.473 回答
0

如果 UserAccount 同时在所有者和受让人中,则查询似乎会重复结果,您可以使用 DISTINCT 过滤重复的结果:

SELECT DISTINCT r FROM ...
于 2013-05-29T16:08:00.617 回答