Quick Contact

    Hibernate

    Hibernate Transaction Management

    What is a transaction?

    A transaction simply represents a unit of work. Generally speaking, a transaction is a set of SQL operations that need to be either executed all successfully or not at all.

    A transaction can be described by ACID properties (Atomicity, Consistency, Isolation, and Durability).</p>
    <h5>Let’s discuss what are ACID properties in detail.

    ACID Properties

    A database must satisfy the ACID properties (Atomicity, Consistency, Isolation, and Durability) to guarantee the success of a database transaction.

    Atomicity:

    Each transaction should be carried out in its entirety; if one part of the transaction fails, then the whole transaction fails.

    Consistency:

    The database should be in a valid state before and after the performed transaction.

    Isolation:

    Each transaction should execute in complete isolation without knowing the existence of other transactions.

    Durability:

    Once the transaction is complete, the changes made by the transaction are permanent (even in the occurrence of unusual events such as power loss).

    Transaction Interface

    In the hibernate framework, we have <i>Transaction</i> interface that defines the unit of work. It maintains abstraction from the transaction implementation (JTA, JDBC).

    A transaction is associated with <i>Session and instantiated by calling session.<i>beginTransaction().</i></p>
    <p>The methods of Transaction interface are as follows:</p>
    <ul>
    <li><i>void begin()</i> – starts a new transaction.</li>
    <li><i>void commit()</i> – ends the unit of work unless we are in FlushMode.NEVER.</li>
    <li><i>void rollback()</i> – forces this transaction to rollback.</li>
    <li><i>voidsetTimeout(int seconds)</i> – it sets a transaction timeout for any transaction started by a subsequent call to begin on this instance.</li>
    <li><i>booleanisAlive()</i> – checks if the transaction is still alive.</li>
    <li><i>voidregisterSynchronization(Synchronization s)</i> – registers a user synchronization callback for this transaction.</li>
    <li><i>booleanwasCommited()</i> – checks if the transaction is committed successfully.</li>
    <li><i>booleanwasRolledBack()</i> – checks if the transaction is rolled back successfully.</li>
    </ul>
    <h5>HibernateTransaction Management CRUD Example</h5>
    <p>The below CRUD source code snippet demonstrates the usage of Transactions in Hibernate applications.</p>
    <p>Consider we have <i>Student</i> JPA entity, let’s persist student object within a transaction.</p>
    <pre>
    publicvoidinsertStudent() {
    Transactiontransaction=null;
    try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
    // start a transaction
    transaction=session.beginTransaction();

    Stringhql=”INSERT INTO Student (firstName, lastName, email) “+
    “SELECT firstName, lastName, email FROM Student”;
    Queryquery=session.createQuery(hql);
    int result =query.executeUpdate();
    System.out.println(“Rows affected: “+ result);

    // commit transaction
    transaction.commit();
    } catch (Exception e) {
    if (transaction !=null) {
    transaction.rollback();
    }
    }
    }
    </pre>
    <p>Consider we have <i>Student</i> JPA entity, let’s update student object within a transaction:</p>
    <pre>
    publicvoidupdateStudent(Student student) {
    Transactiontransaction=null;
    try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
    // start a transaction
    transaction=session.beginTransaction();

    // save the student object
    Stringhql=”UPDATE Student set firstName= :firstName”+”WHERE id = :studentId”;
    Queryquery=session.createQuery(hql);
    query.setParameter(“firstName”, student.getFirstName());
    query.setParameter(“studentId”, 1);
    int result =query.executeUpdate();
    System.out.println(“Rows affected: “+ result);

    // commit transaction
    transaction.commit();
    } catch (Exception e) {
    if (transaction !=null) {
    transaction.rollback();
    }
    }
    }
    </pre>
    <p>Let’s delete student where id = 1;</p>
    <pre>
    publicvoiddeleteStudent(int id) {

    Transactiontransaction=null;
    try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
    // start a transaction
    transaction=session.beginTransaction();

    // Delete a student object
    Studentstudent=session.get(Student.class, id);
    if (student !=null) {
    Stringhql=”DELETE FROM Student “+”WHERE id = :studentId”;
    Queryquery=session.createQuery(hql);
    query.setParameter(“studentId”, id);
    int result =query.executeUpdate();
    System.out.println(“Rows affected: “+ result);
    }

    // commit transaction
    transaction.commit();
    } catch (Exception e) {
    if (transaction !=null) {
    transaction.rollback();
    }
    }
    }
    </pre>
    <p>Let’s get student record from a database.</p>

    publicStudentgetStudent(int id) {
    
    Transactiontransaction=null;
    Studentstudent=null;
    try (Sessionsession=HibernateUtil.getSessionFactory().openSession()) {
    // start a transaction
    transaction=session.beginTransaction();
    
    // get an student object
    Stringhql=" FROM Student S WHERE S.id = :studentId";
    Queryquery=session.createQuery(hql);
    query.setParameter("studentId", id);
    List results =query.getResultList();
    
    if (results !=null&&!results.isEmpty()) {
    student= (Student) results.get(0);
    }
    // commit transaction
    transaction.commit();
    } catch (Exception e) {
    if (transaction !=null) {
    transaction.rollback();
    }
    }
    return student;
    }
    

    Apply now for Advanced Java Training Course

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.