JPQL where子句与集合中的集合 [英] JPQL where clause with collection in collection

查看:90
本文介绍了JPQL where子句与集合中的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用spring数据...我有一个ManyToMany关系实体。

所以我想要做这样的请求:

  @Query(SELECT d FROM Data d WHERE((?2)IS NULL or d.categories IN(?2)))

其中?2 对应一个清单, categories 也是 Data 中的一个(另一个实体)列表。

但是这不起作用......任何想法? :)



PS:我看到一个解决方案:

  @查询( 设定R FROM数据R WHERE(λ3= 0L ORθ3 =(SELECT COUNT(cate.id)FROM数据R2 JOIN r2.categories美食WHERE r.id = r2.id AND美食IN?2)) )

但是这是一个由hibernate产生的蹩脚请求,并不完全是我想要的...

解决方案

查看这是否可行

  @Query(SELECT DISTINCT(d)FROM Data d JOIN d.categories c 
WHERE(COALESCE(?2,NULL)is NULL or c.id IN(?2)))




  1. 这里我假定id是类别表中的主键字段。您可以根据您的情况进行修改。

  2. 您将在此处传递类别ID的列表作为参数。

如果?2为null,则上面的查询将从Data表中检索所有记录,其他将根据您将传递的类别ID列表进行过滤?2。


I use spring data... and I have an entity with ManyToMany relation.

So I wanna do this kind of request:

@Query("SELECT d FROM Data d WHERE ((?2) IS NULL OR d.categories IN (?2))")

where ?2 corresponds to a list and categories is also a list (of another entity) from Data.

But this doesn't work... any idea ? :)

PS: I see a solution with:

@Query("SELECT r FROM Data r WHERE (?3 = 0L OR ?3 = (SELECT COUNT(cate.id) FROM Data r2 JOIN r2.categories cate WHERE r.id = r2.id AND cate IN ?2 ))")

But it's a crappy request generated by hibernate and isn't exactly what I want...

解决方案

See if this works

@Query("SELECT DISTINCT(d) FROM Data d JOIN d.categories c 
WHERE (COALESCE(?2, NULL) IS NULL OR c.id IN (?2))")

  1. Here I am assuming that id is the primary key field in category table. You can modify according to your case.
  2. You will pass the list of category ids as the parameter here.

The above query will retrieve all the records from Data table if ?2 is null other it will filter based on the list of category ids you will pass as ?2.

这篇关于JPQL where子句与集合中的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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