Hibernate Transaction handle example
Published: February 9, 2010 , Updated: January 23, 2010 , Author: mkyong
In Hibernate, the transaction management is quite standard, just remember any exceptions thrown by Hibernate are FATAL, you have to roll back the transaction and close the current session immediately.
Here’s a Hibernate transaction template :
Session session = null; Transaction tx = null; try{ session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); tx.setTimeout(5); //doSomething(session); tx.commit(); }catch(RuntimeException e){ try{ tx.rollback(); }catch(RuntimeException rbe){ log.error("Couldn’t roll back transaction", rbe); } throw e; }finally{ if(session!=null){ session.close(); } }
Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~
[ Read More ] You can find more similar articles at Hibernate Tutorials
Can you please clarify example further? I understand I don’t have to explicitly start or end transaction unless I want to break the unit of work into two parts correct? If there is exception it will rollback and if there is no exception it will commit.
Is this correct? I’m assuming ONLY if I explicitly decide to take over transaction control in application code do I have to do this. So not exactly getting practical significance of this beyond Connection.setAutocommit(false) I do on JDBC connection.
Thanks in advance.
[...] Hibernate Transaction handle example A simple standard example to use Hibernate transaction. [...]