What is transaction management in hibernate

Q. What is transaction management in hibernate? How we get transaction object in hibernate?

Let’s see what is transaction –

  1. Transaction is an interface available in org.hibernate package which is associated with the session.
  2. In the transaction, if any single step fails, the complete transaction will be failed.
  3. We can describe transaction with ACID properties.

A. Atomicity – All success or none.
B. Consistency – Database constraints should not be violated.
C. Isolation – One transaction should not effect another one.
D. Durability – It should in Database after commit.

4. We can get Transaction object with help of session.

Session session = factory.openSession();

Transaction transaction = session.beginTransaction();

5. Transaction object further can be used to call commit() or rollback() method.

transaction.commit();

Let’s see complete example to get Transaction object – 

package manytomanytechhelpzones;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class TransactionExampleInHibernate {

	public static void main(String[] args) {
		
		SessionFactory factory = null;
		
		Session session = null;
		
		Configuration configuration = new Configuration().configure();
		
		try {
			
			factory = configuration.buildSessionFactory();
			
			session = factory.openSession();
			
			Transaction tx = session.beginTransaction();
			
			System.out.println("We have transaction object" + tx);
			
			tx.commit();
			
		} catch (Exception e) {
			
			e.printStackTrace();
			

		} finally {

			session.close();
			
			factory.close();
			
		}
		
	}
	
}

 

In real time development, let’s see how transaction Management works(using Spring).