简体   繁体   中英

spring data jpa and condition for multiple collection

i want to pass a list in which all should match.

  @Query("select g.name as name FROM Gym  g  " +
            "LEFT JOIN g.listOfEquipment   listOfEquipment  " +
            "WHERE " +
            "(((:listOfEquipment) is null) or listOfEquipment.id in (:listOfEquipment)) "+
            "AND (((:listOfAmenity) is null) or listOfAmenity.id in (:listOfAmenity))")
  Page<Map<String, Object>> listing(@Param("listOfEquipment") Set<Integer> listOfEquipment,@Param("listOfAmenity") Set<Integer> listOfAmenity)

above query working for OR but i need AND

suppose i am passing 1,2,3 then result should be all gym who has equipment 1 and 2 and 3 same for amenity also

i tried Finding items with a set containing all elements of a given set with jpql

but its not helping me becuase there are multiple filters

url is

http://localhost:8080/filter?listOfEquipment=5,3&listOfAmenity=51,13&sort=name

This query should give you the Gym.id s matching all the listOfEquipment s assuming the list doesn't contain duplicates.

select g.id as name 
FROM Gym  g 
LEFT JOIN g.listOfEquipment listOfEquipment
WHERE listOfEquipment.id in (:listOfEquipment)) 
GROUP BY g.id
HAVING count(g.id) = #{#listOfEquipment.size}    

You can use it and a similar query for the listOfAmenity as subselects in your main query.

select g.name as name 
FROM Gym  g 
LEFT JOIN g.listOfEquipment listOfEquipment 
WHERE (((:listOfEquipment) is null) 
    OR g.id in (
    select g.id as name 
    FROM Gym  g 
    LEFT JOIN g.listOfEquipment listOfEquipment
    WHERE listOfEquipment.id in (:listOfEquipment)) 
    GROUP BY g.id
    HAVING count(g.id) = #{#listOfEquipment.size}   
)) 
AND (((:listOfAmenity) is null) 
    OR g.id in (
    select g.id as name 
    FROM Gym  g 
    LEFT JOIN g.listOfAmenity listOfAmenity
    WHERE listOfAmenity.id in (:listOfAmenity)) 
    GROUP BY g.id
    HAVING count(g.id) = #{#listOfAmenity.size}   
))

there is a missing bracket in the last AND condition it should be as following

@Query("select g.name as name FROM Gym  g  " +
        "LEFT JOIN g.listOfEquipment   listOfEquipment  " +
        "WHERE " +
        "(((:listOfEquipment) is null) or listOfEquipment.id in        (:listOfEquipment)) "+
        "AND (((:listOfAmenity) is null) or listOfAmenity.id in (:listOfAmenity))")

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