Question

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.

Was it helpful?

Solution

Make sure that you always commit or rollback and then always close your session. Basically, your resources (transaction and session) should be freed no matter what, e.g. they can be placed inside of appropriate finally block (in case of session) or in both try and catch blocks (in case of transaction).

In general, allocation and releasing of resources across different application layers is anti-pattern - if your architecture forces you into applying anti-pattern then there are more questions to ask here... For example, think of what you should do in your "filter" if session happens to be closed...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top