I am using Hibernate in NetBeans. I am using the hibernate util
class that comes with the Hibernate plugin for NetBeans to get the current session. That is, I am using the following code to get my current session:
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
But when I try to lazy fetch anything it gives following error:
org.hibernate.LazyInitializationException: failed to lazily initialize a course.
I am using 2 DAO. One is Abstract DAO and second is CoutseDAO which extends AbstractDAO. code is as follows
public class AbstractDAO<T> {
Session session = null;
public AbstractDAO()
{
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
}
public void createObject(T object)
{
Transaction tx = null;
try
{
tx = session.beginTransaction();
session.save(object);
tx.commit();
}
catch (HibernateException e)
{
tx.rollback();
throw new DataAccessLayerException(e);
}
finally
{
}
}
public void updateObject(T object )
{
Transaction tx = null;
try
{
tx = session.beginTransaction();
session.update(object);
tx.commit();
}
catch (HibernateException e)
{
tx.rollback();
throw new DataAccessLayerException(e);
}
finally
{
}
}
public void deleteObject(T object )
{
Transaction tx = null;
try
{
tx = session.beginTransaction();
session.delete(object);
tx.commit();
}
catch (HibernateException e)
{
tx.rollback();
throw new DataAccessLayerException(e);
}
finally
{
}
}
}
second classs is as follows
public class CourseDAO extends AbstractDAO<Course>{
public CourseDAO()
{
super();
}
public Course findByID(int cid){
Course crc = null;
Transaction tx = null;
try {
tx = session.beginTransaction();
Query q = session.createQuery("from Course as course where course.cid = "+cid+" ");
crc = (Course) q.uniqueResult();
tx.commit();
}
catch (HibernateException e)
{
e.printStackTrace();
tx.rollback();
throw new DataAccessLayerException(e);
}
finally
{
}
return crc;
}
public List<Course> findAll(){
List lst = null;
Transaction tx = null;
try {
tx = session.beginTransaction();
Query q = session.createQuery("from Course ");
lst = q.list();
tx.commit();
}
catch (HibernateException e)
{
e.printStackTrace();
tx.rollback();
throw new DataAccessLayerException(e);
}
finally
{
}
return (List<Course>)lst ;
}
}