Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...