Search code examples
hibernatehibernate-criteria

How to query associated deep parents using Criteria


While using hibernate's Criteria to run the query, to be able to search by parent's attribute, I use this approach:

  List children = session.createCriteria(Child.class)
 .createAlias("parent", "parent")
 .add( Restrictions.eq("parent.name", "name") )
 .list();

But I'm wondering how to support the deep parents query? I use below approach, but it doesn't work.

 List children = session.createCriteria(Child.class)
 .createAlias("parent", "parent")
 .createAlias("grandfather", "grandfather")
 .add( Restrictions.eq("parent.grandfather.name", "name") )
 .list();

Wondering how to support this type of query if I want to query by parent.grandfater.name?


Solution

  • The alias is a JOIN, so use as follow:

      List children = session.createCriteria(Child.class)
     .createAlias("parent", "parent")
     .createAlias("parent.grandfather", "grandfather")
     .add( Restrictions.eq("grandfather.name", "name") )
     .list();