Spring Data JPA Transactions Interview Questions and Answers
Master Spring Data JPA Transactions with interview questions covering @Transactional, transaction propagation, isolation levels, rollback rules, read-only transactions, transaction lifecycle, and production best practices.
Introduction
A transaction is a sequence of database operations that execute as a single logical unit of work.
Consider a banking fund transfer.
The application performs multiple operations:
- Debit money from Account A
- Credit money to Account B
- Create transaction history
- Update audit records
- Publish business events
If any one operation fails, all previous database changes must be rolled back.
Spring Data JPA integrates with Spring's transaction management through the @Transactional annotation.
It guarantees data consistency, integrity, and reliability.
Spring Transaction Architecture
flowchart LR
Application --> Service
Service --> TransactionManager
TransactionManager --> Hibernate
Hibernate --> Database
Q1. What is a Transaction?
Answer
A transaction is a group of database operations executed as a single unit.
A transaction has only two outcomes:
- Commit
- Rollback
If every operation succeeds,
the transaction commits.
If any operation fails,
the transaction rolls back.
Benefits
- Data consistency
- Atomicity
- Reliability
- Isolation
Q2. What is @Transactional?
@Transactional tells Spring to execute a method inside a database transaction.
Example
@Service
public class TransferService {
@Transactional
public void transfer() {
}
}
Spring automatically
- Starts the transaction
- Commits on success
- Rolls back on failure
Q3. How does @Transactional work internally?
Spring creates an AOP proxy around the service.
Workflow
- Client calls service.
- Proxy starts transaction.
- Business logic executes.
- Commit if successful.
- Rollback if exception occurs.
Transaction Flow
sequenceDiagram
Client->>Transaction Proxy: Method Call
Transaction Proxy->>Transaction Manager: Begin Transaction
Transaction Manager->>Service: Execute Method
Service->>Repository: Database Operations
Repository-->>Service: Success
Service-->>Transaction Manager: Complete
Transaction Manager-->>Transaction Proxy: Commit
Transaction Proxy-->>Client: Response
Q4. What are ACID properties?
| Property | Description |
|---|---|
| Atomicity | All or nothing |
| Consistency | Valid state before and after transaction |
| Isolation | Transactions do not interfere |
| Durability | Committed data survives failures |
ACID Model
flowchart TD
Transaction --> Atomicity
Transaction --> Consistency
Transaction --> Isolation
Transaction --> Durability
ACID guarantees reliable transaction processing.
Q5. What are Propagation Types?
Propagation determines how nested transactions behave.
Common propagation modes
| Propagation | Description |
|---|---|
| REQUIRED | Join existing transaction or create new |
| REQUIRES_NEW | Suspend existing and create new transaction |
| SUPPORTS | Join if available |
| NOT_SUPPORTED | Execute without transaction |
| MANDATORY | Must have existing transaction |
| NEVER | Fail if transaction exists |
| NESTED | Nested transaction with savepoint |
Example
@Transactional(
propagation =
Propagation.REQUIRES_NEW)
Q6. What are Isolation Levels?
Isolation controls visibility between concurrent transactions.
| Isolation | Prevents |
|---|---|
| READ_UNCOMMITTED | Nothing |
| READ_COMMITTED | Dirty Reads |
| REPEATABLE_READ | Dirty + Non-repeatable Reads |
| SERIALIZABLE | All concurrency issues |
Example
@Transactional(
isolation =
Isolation.READ_COMMITTED)
Isolation Hierarchy
flowchart TD
READ_UNCOMMITTED --> READ_COMMITTED
READ_COMMITTED --> REPEATABLE_READ
REPEATABLE_READ --> SERIALIZABLE
Higher isolation provides stronger consistency but lower concurrency.
Q7. When does Spring roll back a transaction?
By default,
Spring rolls back for
- RuntimeException
- Error
Checked exceptions do not trigger rollback automatically.
Example
@Transactional(
rollbackFor =
Exception.class)
This ensures rollback even for checked exceptions.
Q8. What is a Read-Only Transaction?
Read-only transactions optimize read operations.
Example
@Transactional(
readOnly = true)
Benefits
- Better Hibernate optimization
- Reduced dirty checking
- Improved performance
Use read-only transactions for queries only.
Q9. What are common Transaction pitfalls?
Common mistakes
- Using
@Transactionalon private methods - Self-invocation bypassing proxies
- Long-running transactions
- Mixing remote API calls inside transactions
- Performing expensive computations before commit
- Forgetting rollback rules
Q10. Transaction Best Practices
Keep Transactions Short
Avoid long-running database locks.
Place Transactions in Service Layer
Repositories should focus only on persistence.
Use Read-Only Transactions
For reporting and query operations.
Handle Exceptions Properly
Configure rollback rules explicitly when needed.
Avoid Remote Calls
Never call external services inside long database transactions.
Banking Example
flowchart TD
TransferService --> TransactionManager
TransactionManager --> DebitAccount
TransactionManager --> CreditAccount
TransactionManager --> TransactionHistory
TransactionManager --> AuditLog
TransactionManager --> Commit
All operations succeed or all are rolled back.
Common Interview Questions
- What is a transaction?
- What is
@Transactional? - How does Spring manage transactions?
- What are ACID properties?
- What are propagation types?
- What are isolation levels?
- When does rollback occur?
- What is a read-only transaction?
- Transaction pitfalls?
- Transaction best practices?
Quick Revision
| Topic | Summary |
|---|---|
| Transaction | Logical unit of work |
| @Transactional | Transaction management |
| ACID | Transaction guarantees |
| Propagation | Nested transaction behavior |
| Isolation | Concurrent transaction visibility |
| Commit | Save changes |
| Rollback | Undo changes |
| ReadOnly | Optimized read transaction |
| Transaction Proxy | Spring AOP transaction management |
| Service Layer | Recommended transaction boundary |
Transaction Lifecycle
sequenceDiagram
Client->>Service: Transfer Money
Service->>Transaction Manager: Begin Transaction
Transaction Manager->>Repository: Debit Account
Repository-->>Transaction Manager: Success
Transaction Manager->>Repository: Credit Account
Repository-->>Transaction Manager: Success
Transaction Manager->>Repository: Save History
Repository-->>Transaction Manager: Success
Transaction Manager->>Database: Commit
Database-->>Client: Transaction Successful
Production Example – Banking Fund Transfer
A banking application transfers $10,000 between customer accounts.
Business Flow
- Validate sender account.
- Debit Account A.
- Credit Account B.
- Insert transaction history.
- Record audit entry.
- Publish a
FundTransferCompletedEvent.
Implementation
@Transactional
public void transferMoney(...) {
debitAccount(...);
creditAccount(...);
saveTransaction(...);
saveAudit(...);
}
If creditAccount() fails due to insufficient database resources or any unexpected exception,
Spring automatically rolls back:
- Debit operation
- Credit operation
- Audit record
- Transaction history
The database remains completely consistent.
flowchart LR
TransferService --> TransactionProxy
TransactionProxy --> TransactionManager
TransactionManager --> Debit
TransactionManager --> Credit
TransactionManager --> TransactionHistory
TransactionManager --> Audit
TransactionManager --> CommitOrRollback
CommitOrRollback --> PostgreSQL
This guarantees that partial fund transfers never occur, protecting financial integrity.
Key Takeaways
- Transactions ensure multiple database operations execute as a single atomic unit.
@Transactionaluses Spring AOP proxies to automatically begin, commit, or roll back transactions.- ACID properties guarantee data consistency, reliability, and durability.
- Propagation controls how nested transactions interact, while Isolation manages concurrent transaction visibility.
- By default, Spring rolls back on RuntimeException and Error. Use
rollbackForfor checked exceptions. - Read-only transactions improve performance for query operations by reducing Hibernate overhead.
- Keep transactions short, avoid remote service calls within transactions, and define transaction boundaries in the service layer.
- Proper transaction management is essential for enterprise applications such as banking, insurance, healthcare, and e-commerce where data integrity is critical.