Pages

Sunday, July 15, 2007

Eager fetching in Hibernate using Criteria queries

One of the easiest way of eager fetching is using the setFetchMode function present with Criteria API's. The whole clutter of reflection which i presented below can be removed by using this.
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=new ArrayList();
fetchList.add(exampleTwo);
initializeFetchList(Criteria criteria, List fetchList); //initialize
List exmpleList = criteria.list() //Executing this gives us List of Example Objects with pre-fetched ExampleTwo Objects in it.
.
.
public void initializeFetchList(Criteria criteria, List fetchList){

for (String entityAttribute : fetchList) {
criteria.setFetchMode(entityAttribute, FetchMode.JOIN);
}

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
}

No comments:

Post a Comment