Java › Standard

JPA and JTA in Spring persistence and transactions

Separate standard JPA from Hibernate, trace XA coordination with JTA, and compare the Jakarta and Spring Transactional annotations.

JPA and JTA in Spring persistence and transactions

JPA defines the persistence contract, Hibernate implements it, and Spring manages how application code enters a transaction. I separate those layers before choosing which @Transactional annotation belongs in a service.

The examples use Spring Boot 3.x, Jakarta Persistence 3.1, Hibernate ORM 6.x, and Jakarta Transactions 2.0.

JPA defines the contract and Hibernate implements it

Jakarta Persistence grew from the JPA specification introduced under JSR 220 and evolved through JSR 338. The jakarta.persistence package provides the APIs and annotations that an application can use across providers.

  1. Mapping annotations describe entities, identifiers, tables, and relationships such as @ManyToOne.
  2. An EntityManager works with a persistence context. It tracks entity identity and states such as new, managed, detached, and removed. The provider synchronizes managed changes with the database when the context flushes.
  3. JPQL queries entities and their properties. The provider translates the query into SQL appropriate for the database.

Hibernate and EclipseLink implement that contract. Spring Data JPA adds repository abstractions on top, including JpaRepository. It still relies on a JPA provider to perform the work.

flowchart TD
    APP["Service layer"] --> REPO["Spring Data JPA"]
    REPO --> API["Jakarta Persistence"]
    API --> H["Hibernate ORM"]
    API -.-> E["EclipseLink"]
    H --> DB["Database"]

The starter brings together the APIs, provider, and repository support. The account example also uses Hibernate’s @DynamicUpdate. It changes SQL generation to include modified columns. That behavior is a provider-specific choice, so I keep it when it serves a measured requirement.

1
2
3
4
5
6
// build.gradle
dependencies {
    // Includes the persistence API, Hibernate ORM, and Spring Data JPA
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    runtimeOnly 'com.h2database:h2'
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// src/main/java/com/example/ledger/domain/Account.java
package com.example.ledger.domain;

import jakarta.persistence.*; // Standard Jakarta Persistence package
import org.hibernate.annotations.DynamicUpdate; // Hibernate-specific annotation

@Entity
@Table(name = "accounts")
@DynamicUpdate // Update changed columns only (Hibernate-specific)
public class Account {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String accountNumber;

    @Column(nullable = false)
    private long balance;

    protected Account() {}

    public Account(String accountNumber, long balance) {
        this.accountNumber = accountNumber;
        this.balance = balance;
    }

    public void withdraw(long amount) {
        if (this.balance < amount) {
            throw new IllegalStateException("Insufficient balance.");
        }
        this.balance -= amount;
    }
}

When a transaction spans several resources

With one database, a resource-local transaction usually suffices. Spring can manage it with JpaTransactionManager or a JDBC transaction manager. If a single unit of work must atomically update two databases or a database and a JMS broker, one local connection cannot coordinate both outcomes.

Jakarta Transactions, historically JTA or JSR 907, defines interfaces such as TransactionManager and UserTransaction. An XA-capable coordinator can enlist resources and drive a two-phase commit.

sequenceDiagram
    participant App as Application
    participant TM as JTA coordinator
    participant DB1 as XA resource A
    participant DB2 as XA resource B
    App->>TM: Request commit
    TM->>DB1: Prepare
    TM->>DB2: Prepare
    DB1-->>TM: Prepared
    DB2-->>TM: Prepared
    TM->>DB1: Commit
    TM->>DB2: Commit
    TM-->>App: Commit completed

In the prepare phase, each enlisted resource decides whether it can commit and records the state needed for recovery. If preparation succeeds across the resources, the coordinator records the decision and tells them to commit. A failed prepare leads to rollback. Recovery matters because a participant can lose contact after preparing and still need to learn the decision.

Holding prepared resources can increase lock time and operational cost. For cross-service work that can tolerate eventual consistency, a local transaction with an Outbox or a saga changes the availability and recovery trade-off. For an XA design, check the capabilities and failure recovery of every participating resource.

Two annotations with different configuration options

Spring recognizes both jakarta.transaction.Transactional and its own annotation. In a Spring application, the annotation affects the transaction when the call passes through the configured interceptors.

OptionJakarta TransactionsSpring
PropagationTxType, including REQUIRED and REQUIRES_NEWPropagation, including NESTED where supported
IsolationNo annotation attributeisolation
Read-only hintNo annotation attributereadOnly
TimeoutNo annotation attributetimeout
Rollback rulesrollbackOn and dontRollbackOnrollbackFor and noRollbackFor
Manager selectionContainer configurationtransactionManager or value can identify a Spring bean

Spring’s readOnly = true can help the configured provider optimize flush and dirty-checking behavior. It can also be a signal to application-specific read-replica routing. The annotation alone does not create that routing or enforce read-only SQL.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// src/main/java/com/example/ledger/service/AccountService.java
package com.example.ledger.service;

import com.example.ledger.domain.Account;
import com.example.ledger.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountService {

    private final AccountRepository accountRepository;

    public AccountService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    // 1. Spring read-only transaction hint
    @Transactional(readOnly = true)
    public Account findAccount(Long id) {
        return accountRepository.findById(id)
            .orElseThrow(() -> new IllegalArgumentException("Account not found."));
    }

    // 2. Spring isolation, timeout, and checked-exception rollback rules
    @Transactional(
        isolation = Isolation.READ_COMMITTED,
        timeout = 5,
        rollbackFor = Exception.class
    )
    public void withdraw(Long id, long amount) {
        Account account = findAccount(id);
        account.withdraw(amount);
    }

    // 3. Jakarta transaction annotation for comparison
    @jakarta.transaction.Transactional(
        value = jakarta.transaction.Transactional.TxType.REQUIRES_NEW,
        rollbackOn = Exception.class
    )
    public void recordAuditLog(Long accountId) {
        // Write the audit record in its own transaction
    }
}

Choosing and checking the transaction boundary

For a Spring service, I use Spring’s annotation when the method needs isolation, read-only behavior, a timeout, or a particular transaction manager. Jakarta’s annotation is a useful choice for a shared module that must express the same boundary across containers. Standardize the imports within a module so developers can read the rollback rules without guessing which annotation they opened.

Check the boundary with a test that calls the managed proxy and forces a failure after changing a record. Verify the final state from a separate transaction. For a coordinated XA transaction, include a failure during prepare and a recovery scenario before treating the two resources as one reliable unit.

This post is licensed under CC BY 4.0 by the author.