liveBook · Manning

Database transaction

As explained in Java Persistence with Spring Data and Hibernate epub

A transaction is a database unit of work whose operations are handled as a coherent atomic interaction.

A database transaction groups operations that must succeed or fail together. Finishing an auction, for example, may involve finding a winning bid, charging a seller, and sending notifications. That business unit of work can span several systems; a database transaction covers the database operations within it, not automatically the external billing or notification steps. section 11.1 section 11.1.2

Listing 10.1 A typical unit of work
Path: managing-data/src/test/java/com/manning/javapersistence/ch10
 /SimpleTransitionsTest.java
 
EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("ch10");
 
// . . .
EntityManager em = emf.createEntityManager();
 
\1 {
    em.getTransaction().begin();
 
    // . . .
    em.getTransaction().commit();
} catch (Exception ex) {
    // Transaction rollback, exception handling
    // . . .
} finally {
    if (em != null && em.isOpen())
        em.close();
}

The Java SE pattern creates an EntityManager, begins a transaction, performs work, commits, and closes the EntityManager in finally. The catch block is a placeholder: real code must roll back and handle the exception. section 10.2.1

The EntityManager has a persistence context that tracks managed entity changes. Hibernate obtains a JDBC connection when SQL is needed, executes lookups and queries, and synchronizes tracked changes with the database when it flushes. Commit triggers dirty checking and synchronization; EntityManager.flush() can force synchronization earlier within a transaction. Flushing is not a substitute for committing. section 10.1 section 10.2.1

Choose boundaries and concurrency behavior deliberately:

  • Begin before the batch of database operations, commit on success, and roll back if execution or commit fails. Keep database transactions short: open transactions consume resources and may block concurrent access through locks. section 11.1.2
  • Select an isolation level with its concurrency tradeoffs in mind. Weaker isolation can improve scalability but permits problems such as lost updates, dirty reads, unrepeatable reads, or phantom reads. section 11.2.1
  • In Spring, use declarative @Transactional boundaries or programmatic TransactionTemplate. Spring rolls back for RuntimeException by default; @Transactional rollback rules can change which exceptions trigger rollback. section 11.4 section 11.4.2

Reading without an explicit transaction is possible with an unsynchronized persistence context: SELECT runs in auto-commit mode, but changes cannot be flushed as an UPDATE without a transaction. A managed entity already in the context can also differ from a scalar query result read from the database. For tests, @Transactional rolls back by default; @Commit or @Rollback(false) changes that outcome. section 11.3.1 section 20.5

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Works through demarcation, rollback, flushing, isolation, and Spring configuration while focusing on transactions spanning one database.
Examples
Uses auction completion, an EntityManager transaction pattern, and rollback-by-default transactional tests.
What it assumes
Assumes Java application code and introduces EntityManager transaction boundaries explicitly.
What you can do after
Apply it via JPA EntityManager or Spring @Transactional to delimit work and control rollback.
How it connects
Connects persistence contexts and dirty checking with transaction isolation and concurrency control.

Also explained in

Compare how 14 books explain database transaction →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.