Search code examples
hibernatecriteriahibernate-criteriarestriction

Hibernate - Criteria with restriction on parent class


I have an obect A with a child B. I create a criteria for B but try to use a restriction on A. However, that does not work :

Criteria criteria = getCurrentSession().createCriteria(B.class, "p");
criteria.add(eq("B.name", nameB));
criteria.add(eq("B.a.name", nameA));

return criteria.list();

I got te following error :

org.hibernate.QueryException: could not resolve property: a.name of: model.B

I have a FetchType.LAZY on the B.a property, if that matters. I tried to change it to FetchType.EAGER but it did not help.


Solution

  • I resolved it thanks to the documentation.

    criteria.add(eq("nom", nomB)).setFetchMode("a", FetchMode.JOIN).createCriteria("a").add(eq("nom", nomA));
    

    FetchMode.JOIN is like FetchMode.EAGER but this last one is deprecated.