Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Flushing and closing a Hibernate session

807580Dec 30 2009 — edited Dec 30 2009
Hi!
I'm looking into an old application that uses methods like the following when saving objects to the database.
    
public void saveMyObject(MyObject myObject) {
        Session session = sessionFactory.openSession();
        try{           
            session.saveOrUpdate("MyObject", myObject);
        } finally {
            session.flush();
            session.close();
        }   
    }
When looking at it I started wondering, what if session.flush() throws an exception? Then close will never be called and the connection remains open?
Or does flush() handle closing the session in case of an exception?
Would it be better to do the flush in a try-catch-ignore kind of clause?

Fetching objects are done like:
    public Collection getSomeOtherObjects() {
        Session session = sessionFactory.openSession();
        try{
            Query listQ =  session.createQuery("from MyOtherObject as MyOtherObject");
            List items = listQ.list();
            return items;
        } finally {
            session.flush();
            session.close();
        }
    }
Is the flush really needed there?

Best,
T
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 27 2010
Added on Dec 30 2009
2 comments
839 views