Make delicious recipes!


Transactions in Hibernate


A group of statements executed within a transaction are either all executed successfully or none of them is executed.
For example, if a transaction looks like the following:

Transaction start
    1) update statement
    2) delete statement
    3) insert statement
    4) select statement
Transaction end

Now, suppose 2nd statement for delete fails.
If the above group of statements were not enclosed in the transaction, then 1st statement would have been executed without the other ones below it.

But since the group of statements is enclosed in a transaction, they will either all pass or all fail.
So, for the above case, if 2nd statement (or any statement) fails, the statements before it are also rolled back.

Hibernate transactions:

Session session = null;
Transaction tx = null;

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

    // statements supposed to be in a transaction, anything like
    // 1) update statement
    // 2) delete statement
    // 3) insert statement
    // 4) select statement

    tx.commit();

} 
catch(RuntimeException e) 
{
    try 
    {
        tx.rollback();
    } 
    catch(RuntimeException rbe)
    {
        log.error("Cannot roll back transaction", rbe);
    }
    throw e;
}
finally
{
    if(session!=null)
    {
        session.close();
    }
}



A word of caution: Transactions should be used carefully as they can cause deadlocks in the system.

Uses: Transactions are required where atomicity of an operation is required.
For example, if A is paying B through a banking account, then receiving of money by B and sending of money by A should either both happen or should both fail.

If A sends and B does not receive, it would be erroneous.
If A does not send but B receives, then also it would be erroneous.

There is no error only when:
  1. A does not send and B does not receive (Both fail)
  2. A sends and B receives (Both pass)






Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal