使用 jpql 查找包含给定集合的所有元素的集合的项目 [英] Finding items with a set containing all elements of a given set with jpql

查看:24
本文介绍了使用 jpql 查找包含给定集合的所有元素的集合的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

以下是简化的类:

@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)

我得到包含任何给定标签的项目.这并不奇怪,但我想要包含 all 给定标签的项目.所以我反过来试试:

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

我收到错误消息 org.hibernate.exception.SQLGrammarException:行 IN 的参数必须全部是行表达式.如果 tags 只包含一个标签,它会起作用,但如果超过这个标签,它就会失败.

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.

如何在 JPQL 中表达这一点?

How can I express this in JPQL?

推荐答案

诀窍是使用计数:

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

这篇关于使用 jpql 查找包含给定集合的所有元素的集合的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆