Suppose I am have created a criteria on a class. Now inside that I want to get data from a different table which I will be using in the current criteria. For that again I have to create criteria on the new table. So is it possible create a new criteria inside a criteria?
Asked
Active
Viewed 413 times
0
-
Try to check subqueries http://stackoverflow.com/a/20427782/1679310 – Radim Köhler Jun 18 '15 at 15:40
-
possible duplicate of [Hibernate nested query using criteria](http://stackoverflow.com/questions/17320272/hibernate-nested-query-using-criteria) – Amogh Jun 18 '15 at 20:22
1 Answers
1
Yes It is possible , see the description below from the hibernate documentation
https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html
15.4. Associations
By navigating associations using createCriteria() you can specify constraints upon related entities:
List cats = sess.createCriteria(Cat.class)
.add( Restrictions.like("name", "F%") )
.createCriteria("kittens")
.add( Restrictions.like("name", "F%") )
.list();
The second createCriteria() returns a new instance of Criteria that refers to the elements of the kittens collection.
There is also an alternate form that is useful in certain circumstances:
List cats = sess.createCriteria(Cat.class)
.createAlias("kittens", "kt")
.createAlias("mate", "mt")
.add( Restrictions.eqProperty("kt.name", "mt.name") )
.list();
(createAlias() does not create a new instance of Criteria.)
The kittens collections held by the Cat instances returned by the previous two queries are not pre-filtered by the criteria. If you want to retrieve just the kittens that match the criteria, you must use a ResultTransformer.
List cats = sess.createCriteria(Cat.class)
.createCriteria("kittens", "kt")
.add( Restrictions.eq("name", "F%") )
.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP)
.list();
Iterator iter = cats.iterator();
while ( iter.hasNext() ) {
Map map = (Map) iter.next();
Cat cat = (Cat) map.get(Criteria.ROOT_ALIAS);
Cat kitten = (Cat) map.get("kt");
}

Alok Jain
- 57
- 2