使用jpql查找包含给定集合的所有元素的集合

编程入门 行业动态 更新时间:2024-10-09 14:25:38
本文介绍了使用jpql查找包含给定集合的所有元素的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

以下是简化的类:

@Entity class Item { @ManyToMany var tags:java.util.Set [Tag] = new java.util.HashSet [Tag]()} @Entity 类标记{ @ManyToMany(mappedBy =tags) var items:java.util.Set [Item] = new java.util.HashSet [Item] }

如果我尝试这样做

从项目中选择不同的我加入i.tags t 其中t((:tags) pre>

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

从项目中选择不同的我加入i.tags t where(:tags)in t

我得到错误信息 org .hibernate.exception.SQLGrammarException:行IN的参数必须都是行表达式。如果标签只包含一个标签,但它失败的次数超过了这个标签,它就可以工作。

我如何表达这在JPQL?

解决方案

诀窍是使用一个计数:

从项目中选择i我加入i.tags t 其中t in:标签组由i.id计数(i.id)=:tagCount

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?

解决方案

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

更多推荐

使用jpql查找包含给定集合的所有元素的集合

本文发布于:2023-11-29 15:50:45,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   jpql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!