Finding items with a set containing all elements of a given set with jpql

若如初见. 提交于 2019-12-17 20:06:03

问题


I want to find the items that contain all the given tags in their tags set.

Here are the simplified classes:

@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]
}

If I try it like this

select distinct i 
from Item i join i.tags t
where t in (:tags)

I get the items that contain any of the given tags. That is not surprising, but I want Items that contain all of the given tags. So I try it the other way around:

select distinct i 
from Item i join i.tags t
where (:tags) in t

I get the error message org.hibernate.exception.SQLGrammarException: arguments of row IN must all be row expressions. It works if tags contains only a single tag, but it fails with more than that.

How can I express this in JPQL?


回答1:


The trick is to use a count:

select i from Item i join i.tags t
where t in :tags group by i.id having count(i.id) = :tagCount



回答2:


I just had the same problem as you. I used the reductio ad absurdum:

select distinct i from Item i where i not in (select i2 from Item i2 join i2.tags t where t not in :tags) 


来源:https://stackoverflow.com/questions/14340156/finding-items-with-a-set-containing-all-elements-of-a-given-set-with-jpql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!