-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 
Author Message
 Post subject: easy question about closing sesssions
PostPosted: Fri Nov 05, 2004 2:27 pm 
Newbie

Joined: Fri Nov 05, 2004 2:13 pm
Posts: 7
Hi,
I'm a Hibernate noobie. Typical Hibernate code I've seen so far might look like this:

Code:
public void save(MyBean myBean) throws Exception {
  Session session = sessionFactory.openSession();
  Transaction tx = session.beginTransaction();   
  session.save(myBean);
  tx.commit();
  session.close();
}

No one seems to use try/finally blocks to close the session if the save() call fails. Isn't this necessary??

Code:
public void save(MyBean myBean) throws Exception {
  Session session = null;
  Transaction tx = null;
  try {
    session = sessionFactory.openSession();
    tx = session.beginTransaction();   
    session.save(myBean);
    tx.commit();
  }
  finally {
    if (session != null)
      session.close();
  }
}


Thanks in advance for any advice,
Eric


Top
 Profile  
 
 Post subject:
PostPosted: Sat Nov 06, 2004 6:44 am 
Senior
Senior

Joined: Sun Jan 04, 2004 2:46 pm
Posts: 147
You are correct, personally I always do

Code:
try
{
    // hibernate logic

    // commit here
}
catch ( HibernateException e )
{
    // rollback here
}
finally
{
    // close session here
}


I think most people use the simplified version to avoid typing out all the exception logic in examples.


Top
 Profile  
 
 Post subject:
PostPosted: Sat Nov 06, 2004 7:26 am 
Hibernate Team
Hibernate Team

Joined: Sun Sep 14, 2003 3:54 am
Posts: 7256
Location: Paris, France
It is very necessary.
Myk pseudo code is better. It rollback the Tx if womething goes wrong.

_________________
Emmanuel


Top
 Profile  
 
 Post subject:
PostPosted: Mon Nov 08, 2004 10:34 am 
Newbie

Joined: Fri Nov 05, 2004 2:13 pm
Posts: 7
thank you!


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.