Search code examples
hibernatecriteria

When using setFetchMode in Hiberate criteria how do I set a restriction on the oneToMany table


I'm struggling to create a Hibernate criteria query that uses setFetchMode(... SELECT) and places a restriction on the returned child records. If I use a creteAlias as recommended it produces an inner join thereby making accurate pagination all but impossible.

The code would be like:-

Criteria criteria = this.getSession().createCriteria(Mother.class);
criteria.addOrder(Order.asc("title"))
// .createAlias("children", "childrenAlias") had to remove
.add(Restrictions.eq("childAge", "5")) // how do I reference childAge?
.setMaxResults(details.getMaxRows())
.setFirstResult(details.getStart())
.setFetchMode("children", FetchMode.SELECT);

Solution

  • God knows where I was at when I posted this. Thought I'd post the answer to tidy up.

    The code I was missing was the following:-

    Criterion child = Restrictions.eq("childAlias.childName", "Albert");
    criteria.createAlias("children", "childAlias", CriteriaSpecification.INNER_JOIN);
    criteria.add(child);