Transaction management in Hibernate

Transaction management in Hibernate

Transaction management in Hibernate ensures that a series of operations either complete successfully or have no effect at all. This is crucial for maintaining data integrity and consistency. Transactions in Hibernate can be managed either programmatically or declaratively:

1. Programmatic Transaction Management : Using Hibernate API to explicitly begin, commit, and rollback transactions.

2. Declarative Transaction Management : Using frameworks like Spring to manage transactions using annotations or XML configuration.

Key Concepts

  • Atomicity : Ensures that all operations within a transaction are completed; if one operation fails, the entire transaction fails.
  • Consistency : Ensures the database transitions from one valid state to another valid state.
  • Isolation : Ensures that the operations in one transaction are isolated from those in another transaction.
  • Durability : Ensures that once a transaction is committed, it will remain so, even in the event of a system failure.

Transaction management

Java Example

Let’s demonstrate programmatic transaction management in Hibernate with an example.

Step 1: Define the Entities

java
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Product {
    @Id
    private int id;
    private String name;
    private double price;

    // Getters and setters
}


Step 2: Configure Hibernate

 hibernate.cfg.xml 

xml
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>
        
        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
        
        <!-- Specify dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Update the database schema on startup -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- Mappings -->
        <mapping class="com.example.Product"/>
    </session-factory>
</hibernate-configuration>

Step 3: Main Application

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

public class Main {
    public static void main(String[] args) {
        // Set up the Hibernate session factory
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = null;

        try {
            session = sessionFactory.openSession();
            session.beginTransaction();

            // Create and save a Product
            Product product = new Product();
            product.setId(1);
            product.setName("Laptop");
            product.setPrice(1500.00);
            session.save(product);

            // Commit the transaction
            session.getTransaction().commit();
        } catch (Exception e) {
            if (session != null) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
            sessionFactory.close();
        }
    }
}

Explanation of Transaction management in Hibernate

1.  Define the Entities : The Product entity represents a product with id, name, and price fields.

2.  Configure Hibernate : The hibernate.cfg.xml file configures Hibernate to connect to a MySQL database and update the schema on startup.

3.  Main Application :

  • Session Management : We open a session and begin a transaction.
  • Entity Operations : We create and save a Product entity.
  • Transaction Management : We commit the transaction if successful; otherwise, we rollback in case of an exception.

This example demonstrates basic transaction management in Hibernate, ensuring that operations within a transaction are completed successfully or rolled back in case of failure.

Homepage

Readmore