Thursday, June 2, 2011

Hibernate Criteria with Complex Object Restrictions

So here is the deal, you want to create a hibernate criteria statement with some restrictions. These are no ordinary restrictions though, these are properties of other properties in your class; So something like the following:


 public class Person{
    private UserInfo userInfo;

    //Getters and setters omitted
 }



public class UserInfo {
    private String username;
}


You want to load a Person object by setting a restriction on the username property of the UserInfo class. So at first you might try something like this:


Criteria personCriteria = getCurrentSession().createCriteria(Person.class)
      .add(Restrictions.ilike("userInfo.username", "someUserNameGoesHere"));


What happens when you do that is hibernate throws up all over itself. Here is the way to make it work:


Criteria countCriteria = getCurrentSession().createCriteria(Person.class)
      .createAlias("userInfo", "ui")
      .add(Restrictions.ilike("ui.username", "someUserNameGoesHere"));


So all that really needs to be done is create an alias for the UserInfo entity and reference that in your restriction statement, DONE!