views:

475

answers:

2

i am using the following approach to sole lazy initialization problem in hibernate.Pleas 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()
{

  this.session =    this.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())
          HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();

IS this approach right?? Can it can have any problem

A: 

could you explain why do you need to have ur transactions in ur repositories? the problem there is that they are going to be so fine-grained, so you are not gonna get any advantage from the session caching

then you are opening the transaction there but closing it in your filter. what happens if you access multiple repositories in your service? Maybe i am not understanding what you mean but i think you need to re-think the reasons that force you to manage your transactions in your repositories

Yannis
A: 

When do you create you CourseDAO? If it is a singleton bean or something else that lives longer than a page view, it will need to keep a SessionFactory and generate a new Session when it needs one rather than keeping a Session.

Rasmus Kaj