Hibernate Criteria equivalent for IN clause in Subqueries?
25,665
The criteria API does not have a provision to add another query as a restriction.. i think what @Niroshan Abayakoon was trying to say is that you need to execute the queries for the IN
clause seperatly & add the result to the Restrictions.in()
condition.
List<?> entity2Data=//get data from either a query or criteria
List<?> entity3Data=//get data from either a query or criteria
Criteria c = // obtain criteria from session
// basically creates an OR condition chain
Disjunction orConditions = Restrctions.disjunction();
orConditions.add(Restrictions.in("obj", entity2Data));
orConditions.add(Restrictions.in("obj", entity3Data));
c.add(orConditions);
this would get hibernate to consider the list within the IN
clause.
Its always better to fallback to HQL in situations like this.
Author by
Mr.Eddart
Updated on September 09, 2020Comments
-
Mr.Eddart over 3 years
I would like to translate a query like this one:
FROM Entity_1 obj WHERE obj IN (FROM Entity2) OR obj IN (FROM Entity3)
To hibernate Criteria form, and the official documentation of Hibernate is not enough because it doesn't say how to apply the
IN
statement.Any hint?
-
Mr.Eddart over 12 yearsThank you very much. But I still don't understand that "createCriteria(null)", why the null parameter? when do I query the Entity1? why the second createCriteria is independent from the first? i need to do obtain a single list at the end. Thanks!
-
Mr.Eddart over 12 yearsStill problem, because
Restrictions.in(String, String)
expects a propertyName as first parameter (and I suppose you are trying to pass Entity2.class or "Entity", neither of them would work). -
Anantha Sharma over 12 yearshere
Entity2 and Entity3
are considered to be a string containing the name of the property.. i've updated my answer. -
Mr.Eddart over 12 yearsYes, but if you look at my initial HQL query, there are not such "someProperty" nor "anotherProperty". I cannot apply this solution to translate my query... am i mistaken? Thanks.
-
Anantha Sharma over 12 yearsnot exactly... the property name can be anything... i;ve edited my answer again... probably this was what you were looking for.
-
Mr.Eddart over 12 yearsRight, this maybe is the solution. Thanks a lot. I cannot use it anyway because i need the query to execute in a sinble invokation to database. Nevertheless, i will suppose that there is not possible solution for this in Criteria and that i will have to do it in HSQL. I will take this as the correct answer if nothing better arises. BTW, i have opened a new question explaining the problem a bit more just in case you want to extend or comment something: stackoverflow.com/questions/7346281/…