Main Tutorials

Hibernate Transaction handle example

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();
    		}
    	}

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
12 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Mike
4 years ago

Hello
I have RollBack exception Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Can’t call rollback when autocommit=true
I use property name=”hibernate.current_session_context_class” thread

My code:
Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();

try {
session.getTransaction().begin();

session.createQuery (“……”);

//Here some code create Exception and my transaction try to rollback

session.getTransaction().commit();
} catch (Exception e) {

session.getTransaction().rollback();
}

Karan
4 years ago

I want to do rollback all persist in multithreading if one thread got exception

Arpit Gupta
9 years ago

Dear mkyong

I have a question. if i set auto commit = true then if any exception is came then transaction.commit is not run because of exception, run only catch block then what’s the means of transaction.roleback it never be used because transaction.commit is not run because of exception. look the code…

Session session = null;
Transaction tx = null;

try{
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
tx.setTimeout(5);

if(true){
throw new Exception(“My Exception”);
}

tx.commit(); // this is not execute because of exception

}catch(RuntimeException e){
try{
tx.rollback(); // if transaction is not commit then what is the means of rollback ??????????……
}catch(RuntimeException rbe){
log.error(“Couldn’t roll back transaction”, rbe);
}
throw e;
}finally{
if(session!=null){
session.close();
}
}

Thanks in advance..

Gowtham
9 years ago
Reply to  Arpit Gupta

Store the TX.commit in a variable and if it is NOT NULL , then perform the “tx.commit” in the Catch block

Trung Pham
9 years ago

thank you 🙂

Abdul
10 years ago

Can we use the concept of savepoint in hibernate if yes then how?

balaguruparan
10 years ago

Thalaiva,
you are the great,
but this google adds are making your website ugly, please unsubscribe from google adds, they are posting ads with some ugly pictures.

your fan
Bala…

sandeep
8 years ago
Reply to  balaguruparan

hey dud,
do one thing, just add a plugin into your browser to stop the ads…..i.e adblock plus for firefox and google chrome as well

shahin
11 years ago

Dear mkyong
I have question. If two or more user try to insert same time same table using same form from differet pc how hibernate will manage this transaction?

Thanks in advance

Purushottam
10 years ago
Reply to  shahin

Its uses versioning mechanism to differentiate updates on same data

Arby
12 years ago

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.

Sean Anderson
11 years ago
Reply to  Arby

Hey Arby,

Transactions assure that persistence of multiple objects (rows) to numerous tables all get completed. Otherwise the framework “rolls back” any that were saved in light of the ones which were not saved. For instance, if you are going to persist an invoice which consists of multiple rows for the invoice sales items in one table plus a row for the invoice specific information in another table (customer, invoice number, date, etc..), that none of it is recorded if any of it fails–since it takes time for each save and anything can happen (machine loses power, etc..) before the next save. Transactions are meant to ensure data quality and consistency. Otherwise, if an invoice save halfway failed the user could pull up an invoice in the system which had no sales items! Not cool.