10

我想在其标签集中找到包含所有给定标签的项目。

以下是简化的类:

@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 中表达这一点?

4

2 回答 2

19

诀窍是使用计数:

select i from Item i join i.tags t
where t in :tags group by i.id having count(i.id) = :tagCount
于 2013-01-15T21:51:24.980 回答
4

我刚遇到和你一样的问题。我使用了荒谬的归约法:

select distinct i from Item i where i not in (select i2 from Item i2 join i2.tags t where t not in :tags) 
于 2013-11-29T13:42:27.637 回答