Hibernate Criteria and Composite Properties

Criteria queries are enormously useful feature in Hibernate, as they allow you to dynamically build up a complex query. They are very useful, for instance, when you have a search form UI (or a set of search forms) and you want to build up a search query from any combination of the search parameters contained in the form. However, there is one feature regarding Criteria queries which is non-obvious – you need to create a sub-Criteria for each composite property that you wish to map. For instance, the code below will not work:

Criteria hibCriteria = getDao().createCriteria(Event.class);
hibCriteria.add(Expression.like("title", name));
hibCriteria.add(Expression.ge("calendar.startDate", startDate);
hibCriteria.add(Expression.le("calendar.endDate", endDate);

If you want to reference a nested property in a Criteria query, you need to create a separate Criteria instance for each property:

Criteria hibCriteria = getDao().createCriteria(Event.class);
hibCriteria.add(Expression.like("title", name));

// Add a sub-criteria for the nested property set
Criteria calCriteria = hibCriteria.createCriteria("calendar");
calCriteria.add(Expression.ge("startDate", startDate);
calCriteria.add(Expression.le("endDate", endDate);