Hibernate Criteria API: adding criteria for a property of a related (mapped) entity.

Let’s say Content entity contains Label entities (as “labels”), the relationship might be one-to-many or many-to-many.
In this case the code below won’t work:

session.createCriteria(Content.class)
.add(Restrictions.eq("labels.labelId", labelId))
.list();

It should be as follows:

session.createCriteria(Content.class)
.createAlias("labels", "x")
.add(Restrictions.eq("x.labelId", labelId))
.list();

OR

session.createCriteria(Content.class)
.createCriteria("labels")
.add(Restrictions.eq("labelId", labelId))
.list();

NOTE:
In the second statement above, if we try to add one more clause that belong to Content class, we should be careful. It should be added after createCriteria(Content.class) statment and before createCriteria(“labels”). This is because if we add if after, it will belong to “labels” object.

Leave a comment