我想找到在其标签集中包含所有给定标签的项目。
这里是简化的类:
@Entity
class Item {
@ManyToMany
var tags: java.util.Set[Tag] = new java.util.HashSet[Tag]()
}
@Entity
class Tag {
@ManyToMany(mappedBy="tags")
var items: java.util.Set[Item] = new java.util.HashSet[Item]
}
如果我这样尝试
select distinct i
from Item i join i.tags t
where t in (:tags)
我得到包含任何给定标签的项目。这并不奇怪,但我想要包含所有 给定标签的项目。所以我反过来试试:
select distinct i
from Item i join i.tags t
where (:tags) in t
我收到错误消息 org.hibernate.exception.SQLGrammarException: arguments of row IN must all be row expressions
。如果 tags
只包含一个标签,它就可以工作,但如果包含多个标签,它就会失败。
我如何用 JPQL 表达它?
最佳答案
诀窍是使用计数:
select i from Item i join i.tags t
where t in :tags group by i.id having count(i.id) = :tagCount
关于java - 使用jpql查找包含给定集合的所有元素的集合的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14340156/