Hi Guys! I am back with a new post titled “Accessing indirect properties using Criteria”. In Hibernate Criteria when we try to reference an indirect property of an object(A property that is part of another mapped object) then we get the following exception:-

Nested exception is org.hibernate.QueryException: could not resolve property: “Nested Property” of: “Classname”

The above exception is very common and there are several posts related to it on Stack Overflow. The actual reason of the exception is that when createCriteria() method is invoked with the class Name as parameter then it returns a new instance of Criteria that only refers to the elements of the class passed as a parameter(excluding any mapped class). So if we want to apply some condition on a nested object we can do so in the following ways:-

1st Approach(Creating Alias):-

List orders = sess.createCriteria(Order.class)
.createAlias("item", "it")
.add( Restrictions.gt("it.price", 5000) )

sess: Session is obtained from Session Factory and is used to interact with the database like save, retrieve etc. It is a bridge between object and table.

In the above example we are fetching those orders whose item price is greater than 5000. When we apply a restriction on the attributes of item we create an alias because item field does not belong to Order class but it is a separate Class mapped with the Order class.

2nd Approach(Use Nested createCriteria):-

List orders = getSession().createCriteria(Order.class)
.add( Restrictions.like("description", "PlayStation%") )
.add( Restrictions.like("name", "V%") )

In the above example we are fetching those orders whose customer name starts with “V”. We used createCriteria on customer field and then we can apply Restrictions on the attributes of customer field.

Both the above method should work flawlessly.
Happy Coding 🙂