我有以下课程:
@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;
}
我有一个用户帐户,我希望能够支持所有在所有者或受让人中拥有该用户的Entity对象。
我试过这个,几乎可以工作,但似乎回到某种笛卡尔结果:
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";
谁能告诉我我做错了什么?
答案 0 :(得分:0)
如果UserAccount在所有者和受让人中,看起来查询将复制结果,您可以使用DISTINCT过滤重复的结果:
SELECT DISTINCT r FROM ...
答案 1 :(得分: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就足够了。