четверг, 27 марта 2014 г.

How to override loading nested lazy collections and sub-collections using Hibernate Criteria API

public class Module {
private Long id;
private List<Element> elements;
........................
}

public class Element {
........................
private List<Unit> units;
........................
}

public class Unit {
........................
}

These collections are marked lazy by default in mapping XML files, and you cannot change this behaviour. If you want Hibernate to load them fully initialized, you can use following code: 

// Load sample
Long moduleID = 1L;
Criteria criteria = session.createCriteria(Module.class, "module")
.setFetchMode("module.elements", FetchMode.JOIN)
.createAlias("module.elements", "element", CriteriaSpecification.LEFT_JOIN)
.setFetchMode("element.units", FetchMode.JOIN)
.add(Property.forName("module.id").eq(moduleID ));

List<Module> storedModules = (List<Module>) criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY).list();