Thursday, 21 February 2013

When to use of initialize() method of Hibernate class

Suppose we have one class


public class Productmapping implements java.io.Serializable {

private Integer id;
private Customermaster customermaster;
private String abcValue;
private String xyzValue;
private boolean isDeleted;

         ..
         ..
         .... getter/setter

 @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customerId", nullable = false)
public Customermaster getCustomermaster() {
return this.customermaster;
}

public void setCustomermaster(Customermaster customermaster) {
this.customermaster = customermaster;
}
     
}


Here we declare FetchType = Lazy, so by default customermaster object of Productmapping class remains uninitialized when we retrieve productmapping object.


Now we want to retrieve single object(row) of Productmapping class which is initialized with customermaster object of class Customermaster.

Simply write one method in DAO class like...


public Productmapping getProductMappingFromId(int id) {

Productmapping productmapping = null;

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx=null;
try
{
tx = session.beginTransaction();

productmapping = (Productmapping)session.createCriteria(Productmapping.class)
.add(Restrictions.eq("id", id))
.add(Restrictions.eq("isDeleted", false))
.uniqueResult();

Hibernate.initialize(productmapping.getCustomermaster());


tx.commit();

}catch (Exception e) {
e.printStackTrace();
}

return productmapping ;
}


and you will get productmapping object initialized with Connectionmapping object.

Note : Must have to write Hibernate.initialize() method before committing transaction.