But the criteria queries when doing eager loading gives duplicate resultsets, what i mean is if the parent table has one row and the child table associated with it has say 2 rows then on doing an eager fetch we receive 2 parent Objects representing the parent table. This is because, eager fetching is nothing but putting 'sql join' on the underlying tables. And, as a result of this outer joins we get duplicate results. To get distinct results we have to use resultTransformer. The same code is given below.
.
.
Class Example{//Associated with Table EXAMPLE in Example.hbm.xml
private String attributeOne;
private ExampleTwo exampleTwo; //A foreign one to one relation with ExampleTwo
//Getters and Setters
}
.
Class ExampleTwo{//Associated with Table EXAMPLE_TWO in Example.hbm.xml
private String attributeOne;
//Getters and Setters
}
.
Criteria criteria = session.createCriteria(Example.class); //Create the criteria query
List
fetchList.add(exampleTwo);
initializeFetchList(Criteria criteria, List
List
.
.
public void initializeFetchList(Criteria criteria, List
for (String entityAttribute : fetchList) {
criteria.setFetchMode(entityAttribute, FetchMode.JOIN);
}
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
}
No comments:
Post a Comment