Manual JPA Transaction vs Declarative @Transactional
Replace verbose begin/commit/rollback blocks with a single @Transactional annotation.
Porównanie kodu
✕ 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) {
var src = em.find(Account.class, from);
var dst = em.find(Account.class, to);
src.debit(amount);
dst.credit(amount);
}
}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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.
Stare podejście
Manual Transaction
Nowoczesne podejście
@Transactional
Od JDK
11
Poziom trudności
Średniozaawansowany
Wsparcie JDK
Manual JPA Transaction vs Declarative @Transactional
Dostępne
Widely available since Jakarta EE 8 / Java 11
Jak to działa
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.
Powiązana dokumentacja