Search code examples
javahibernatehibernate-criteria

Hibernate criteria query. After creating a sub-criteria, can I return to the original criteria?


In Hibernate tutorial there is an example of sub-criteria.

But after creating the sub-criteria on "kittens", can I return to the original one? If I write a line .add(Restrictions.like("id", 1)) , does it restrict Cat.id or Cat.kittens.id? Is there a way to go back and restrict cat.id again?

List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "F%") )
    .createCriteria("kittens") 
        .add( Restrictions.like("name", "F%") ) 
    .add(Restrictions.like("id", 1)) // on Cat.id or Cat.kittens.id?
    .list();

Solution

  • To avoid confusion add a critiria like below code

        List cats = sess.createCriteria(Cat.class).createCriteria("cat")
    .add( Restrictions.like("name", "F%") )
    .createCriteria("kittens") 
        .add( Restrictions.like("name", "F%") ) 
    .add(Restrictions.like("cat.id", 1)) // on Cat.id or Cat.kittens.id?
    .list();
    

    Hope this will help.