Enterprise intermediate

Manual JPA Transaction vs Declarative @Transactional

Replace verbose begin/commit/rollback blocks with a single @Transactional annotation.

✕ Java EE
@PersistenceContext
EntityManager em;

public void transferFunds(Long from, Long to,
                          BigDecimal amount) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    try {
        Account src = em.find(Account.class, from);
        Account dst = em.find(Account.class, to);
        src.debit(amount);
        dst.credit(amount);
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        throw e;
    }
}
✓ Jakarta EE 8+
@ApplicationScoped
public class AccountService {
    @PersistenceContext
    EntityManager em;

    @Transactional
    public void transferFunds(Long from, Long to,
                              BigDecimal amount) {
        Account src = em.find(Account.class, from);
        Account dst = em.find(Account.class, to);
        src.debit(amount);
        dst.credit(amount);
    }
}
🗑️

No boilerplate

One annotation replaces repetitive begin/commit/rollback try-catch blocks.

🛡️

Safer rollback

The container guarantees rollback on unchecked exceptions — no risk of forgetting the catch block.

📐

Declarative control

Propagation, isolation, and rollback rules are expressed as annotation attributes.

Old Approach
Manual Transaction
Modern Approach
@Transactional
Since JDK
11
Difficulty
intermediate
Manual JPA Transaction vs Declarative @Transactional
Available

Widely available since Jakarta EE 8 / Java 11

Manual transaction management requires explicit begin(), commit(), and rollback() calls wrapped in try-catch blocks — every service method repeats this boilerplate. The @Transactional annotation delegates lifecycle management to the container: it begins a transaction before the method, commits on success, and rolls back on RuntimeException automatically.

Share 𝕏 🦋 in