Hibernate Transaction

In this tutorial you will learn about the Transaction in Hibernate.

Hibernate Transaction

Hibernate Transaction

In this tutorial you will learn about the Transaction in Hibernate.

In transaction multiple operations are gathered into a single unit of work. On failure of operation in the batch Hibernate throws exceptions, any exceptions, are FATAL. In this case transaction is need to be rolled back and the unit of work is stopped as well as the the current session is closed instantly. Hibernate supports several notions of transactions such as JDBC transactions, Java Transaction API (JTA). Few application servers and standalone applications supports only JDBC transactions and few supports only the JTA.

Hibernate provides a way to abstract the transaction management from the environment by implementing an interface Transaction. Each transaction is managed within a Session and it is started by calling a method Session.beginTransaction(). This interface provides the various methods some of them are as follows :

  • begin()
  • commit()
  • rollback()
  • getTimeout()

Example :

Here I am giving simple code as example that will demonstrate how may you use the Hibernate Transaction.

package roseindia.net;

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

public class PersonDetail
{
private static SessionFactory sessionFactory = null;
public static void main(String[] args)
{ 
Session session = null;
Transaction tx = null;
try 
{
try
{
PersonFactory factory = new PersonFactory();
sessionFactory = factory.getSessionFactory();
session = sessionFactory.openSession();
Person person = new Person();
System.out.println("Inserting Record");
tx = session.beginTransaction();
person.setId(1);
person.setName("Roseindia");
session.save(person);
tx.commit();
System.out.println("Done");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
finally
{
session.close();
}
}
}