Friday, April 27, 2012

How to override hbm LAZY loading conf programmatically in Hibernate?

 //1. create conf object
  Configuration cfg = new Configuration();
cfg.configure();
cfg.buildMappings();
Iterator iter;
/*
* iter= cfg.getClassMappings(); while (iter.hasNext()) {
* PersistentClass persistentClass = (PersistentClass) iter.next();
* persistentClass.setLazy(true); Iterator iter2 =
* persistentClass.getPropertyIterator(); while (iter2.hasNext()) {
* Property prop = (Property) iter2.next(); prop.setLazy(true);
* org.hibernate.mapping.Value val = prop.getValue(); if (val != null &&
* val instanceof Fetchable) { Fetchable f = (Fetchable) val;
* f.setLazy(true); } } }
*/

//2. get all collection mappings
iter = cfg.getCollectionMappings();
while (iter.hasNext()) {
Collection collection = (Collection) iter.next();
 //3. set Lazy load to true or false as you wish
collection.setLazy(true);
}
//4. create SessionFactory object
SessionFactory sessionFactor = cfg.buildSessionFactory();

//5. create session object

Session session = sf.openSession();

//6. query to DB using get method. here you will get only  Employee object and remaining all objects proxy's will be created. Untill you call getXXX() the second query won't execute
Employee emp=( Employee ) session.get(Employee.class, 11356L);

1 comment:

Unknown said...

How to do this with Spring mvc 3.0 ,spring-data-jpa 1.3.2.RELEASE,Hibernate 4.3.0.Final