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

以下是简化的类:

@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

10-08 02:49