i am using the following approach to solve lazy initialization problem in hibernate. Please tell me whether it will work or not . I have to implement my transcation in my persistance layer compulsary due to some reasons.
public class CourseDAO {
Session session = null;
public CourseDAO() {
session = HibernateUtil.getSessionFactory().getCurrentSession();
}
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();
//note that i am not commiting my transcation here.
//Because If i do that i will not be able to do lazy fetch
}
catch (HibernateException e) {
e.printStackTrace();
tx.rollback();
throw new DataAccessLayerException(e);
}
finally {
return crc;
}
}
}
and in the filter i am using the folling code
session = HibernateUtil.getSessionFactory().getCurrentSession();
if(session.isOpen())
session.getTransaction().commit();
Is this approach right? Can it can have any problem.