简体   繁体   中英

JPQL where clause with collection in collection

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...

You should use two queries. One you use when the parameter is empty to retrieve all data, and the other when it is not empty to retrieve filtered data.

I think you should better split the complexity. Have a java help :) the containtAll() method doesn't help you?

PS: Does Hibernate understand (?2) IS NULL and works fine for you?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM