tags:

views:

238

answers:

2

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.

A: 

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...

grigory
hey i cannot close or commit the transcation in finaly or catch or try block as it throw a LAzay initialization exception. This is because i am trying to lazy fetch and if i close or commit the session i want be able to lazy fetc, So i was trying to close the session (if it is not closed )in the filter.Is my apporach right??Waithing for your comment
You do in the filter eventually, right? If not then your approach is not right. If you do then your approach is at least feasible. My answer was made for your case anyway.
grigory
A: 

Best practices on the matter, with concrete code examples, are described in the Hibernate docs.

Bozho