Search code examples
hibernatemany-to-manywhere-in

Hibernate(HQL) - how to query "where many in()" many to many



I have a user entity that has many cars.
I cant fetch the user by car list with "IN" statement.

List<Car> cars = getCarsList();
String hql = "From User WHERE user.cars in(:cars)";
Query query = session.createQuery(hql)
query.setParameterList("cars",cars);
//query.setParameterList("cars",cars.toArray());//not working also
//query.setParameter("cars","1,4,8,30");//not working also
query.setMaxResults(1);

In this way, the parameter is cars being ignored.
I have also tries to send vars.toArray();
And I also tried to send String 1,4,8,300 (Ids if cars).


Solution

  • The user alias is not defined. Try with

    String hql = "from User user inner join user.cars car where car.id in (:carIds)";
    Query query = session.createQuery(hql)
    query.setParameterList("cars", carIds);
    

    where carIds is a collection (and not a string as in your third try) containing the IDs of the cars.