0

I'm wondering if is possible to make this kind of evaluation with collections like the query isn't working in my project at a class named query as follow:

@NamedQueries(value = {  
@NamedQuery(
name = "Foo.getBarList", 
query = "select f from Foo f where (:barlist is null or f.barlist.id in (:barslist)) " )})

from this both post:

FROM Foo WHERE Id = :id AND (:barlist is null or Bar in (:barlist)) JPA where clause any

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

I guess the problem was the id in query so I remove and the error stop, just change this:
"select f from Foo f where (:barlist is null or f.barlist in (:barslist)) "

Community
  • 1
  • 1

1 Answers1

1

instead of in HQL you can check

if(barlist==null){
    //query=FROM Foo WHERE Id = :id
}else{
   //query=FROM Foo WHERE Id = :id AND Bar in :barlist
   // query.setParameterList(:barlist",<list object>)
}
Musaddique
  • 1,295
  • 1
  • 11
  • 28
  • Thanks to point a way, but I will end with 2 named queries like: `@NamedQueries(value = { @NamedQuery(name = "Foo.get", query = "select e from Foo e " + " where (:id is null or e.id = :id) " ), @NamedQuery(name = "Foo.getBarList", query = "select e from Foo e " + " where (:id is null or e.id = :id) " + " and (:barlist is null or e.barlist.id in (:barslist)) " )})` and the DAO code will handle a strategy if then else there too. – André Luís Tomaz Dionisio Nov 29 '16 at 12:23
  • the DAO code will handle a strategy if then else there too as like: `Session session = sessionFactory.openSession(); String sql = ""; if(f.getBarList().isEmpty()) sql = "Foo.get"; else sql = "Foo.getBarList"; Query query = session.getNamedQuery(sql); if(!f.getBarList().isEmpty()) query.setParameterList("barlist", f.getBarList());` – André Luís Tomaz Dionisio Nov 29 '16 at 12:24
  • 1
    you can also try this to check whether parameter is there in query .. https://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Query.html#getNamedParameters() – Musaddique Dec 01 '16 at 04:49