JPA Transactions Interview Questions and Answers
Master JPA Transactions with interview questions covering ACID properties, @Transactional, propagation, isolation levels, commit, rollback, flush, transaction boundaries, and production best practices.
Introduction
A transaction is a sequence of database operations executed as a single unit of work. In enterprise applications, transactions ensure that either all operations succeed or none of them are applied, maintaining data consistency and integrity.
Spring Boot applications commonly use the @Transactional annotation, while JPA internally coordinates with the EntityManager, Persistence Context, and the underlying database transaction.
Transactions are fundamental in banking, payment processing, order management, inventory systems, and any application where multiple database operations must remain consistent.
Transaction Architecture
flowchart LR
Application --> Service
Service --> "@Transactional"
@Transactional --> EntityManager
EntityManager --> PersistenceContext
PersistenceContext --> Database
Database --> Commit
Q1. What is a Transaction?
Answer
A transaction is a logical unit of work that groups one or more database operations.
A transaction guarantees that all operations either succeed together or fail together.
Example:
- Debit Account A
- Credit Account B
- Save Transaction History
If any operation fails, everything is rolled back.
Banking Example
flowchart TD
TransferMoney["Transfer Money"] --> DebitAccount["Debit Account"]
DebitAccount["Debit Account"] --> CreditAccount["Credit Account"]
CreditAccount["Credit Account"] --> SaveAudit["Save Audit"]
SaveAudit["Save Audit"] --> Commit
Q2. What are ACID Properties?
| Property | Meaning |
|---|---|
| Atomicity | All or nothing |
| Consistency | Valid state before and after |
| Isolation | Concurrent transactions don't interfere |
| Durability | Committed data survives failures |
Example
Money Transfer
Debit = Success
Credit = Failed
↓
Rollback Debit
This preserves consistency.
Q3. What does @Transactional do?
@Transactional automatically begins and ends a transaction.
Example
@Service
public class AccountService {
@Transactional
public void transfer() {
// business logic
}
}
Spring automatically
- Begins transaction
- Opens persistence context
- Executes SQL
- Flushes changes
- Commits transaction
- Rolls back on exceptions
Q4. What is Commit?
Commit permanently saves all transaction changes.
Example
sequenceDiagram
Application->>Database: Begin
Application->>Database: INSERT
Application->>Database: UPDATE
Application->>Database: COMMIT
Once committed, changes become permanent.
Q5. What is Rollback?
Rollback cancels all transaction changes.
Example
@Transactional
public void transfer(){
debit();
throw new RuntimeException();
credit();
}
Result
Debit ❌
Credit ❌
Everything Rolled Back
Q6. What is the relationship between Transactions and Persistence Context?
Every transaction usually has one persistence context.
Flow
flowchart LR
Transaction --> PersistenceContext["Persistence Context"]
PersistenceContext["Persistence Context"] --> ManagedEntities["Managed Entities"]
ManagedEntities["Managed Entities"] --> Flush
Flush --> Commit
During the transaction
- Entities become managed
- Dirty checking works
- First-level cache is active
Q7. What is Flush vs Commit?
| Flush | Commit |
|---|---|
| Synchronizes SQL | Permanently saves |
| Transaction still active | Transaction ends |
| Can happen multiple times | Happens once |
| Can still rollback | Cannot rollback after commit |
Example
entityManager.flush();
does NOT commit.
Q8. What are Transaction Propagation Types?
Common propagation modes
| Propagation | Description |
|---|---|
| REQUIRED | Join existing transaction or create one |
| REQUIRES_NEW | Always create new transaction |
| SUPPORTS | Use existing if available |
| NOT_SUPPORTED | Suspend transaction |
| MANDATORY | Existing transaction required |
| NEVER | Must not have transaction |
Most applications use
@Transactional(
propagation =
Propagation.REQUIRED
)
Q9. What are Isolation Levels?
Isolation controls concurrent transaction visibility.
| Isolation | Prevents |
|---|---|
| READ_UNCOMMITTED | Nothing |
| READ_COMMITTED | Dirty Reads |
| REPEATABLE_READ | Non-repeatable Reads |
| SERIALIZABLE | Phantom Reads |
Example
@Transactional(
isolation =
Isolation.READ_COMMITTED
)
Higher isolation increases consistency but may reduce performance.
Q10. Transaction Best Practices
Keep Transactions Short
Avoid long-running transactions.
Do Not Perform Remote Calls
Bad
@Transactional
public void process(){
save();
callExternalAPI();
}
The database transaction remains open while waiting for the remote service.
Avoid Large Transactions
Instead of processing one million rows in one transaction, process data in batches.
Use Read-Only Transactions
@Transactional(
readOnly = true
)
Useful for queries only.
Handle Exceptions Properly
Spring rolls back automatically for unchecked exceptions.
For checked exceptions
@Transactional(
rollbackFor =
Exception.class
)
Banking Example
flowchart TD
Transfer --> Debit
Debit --> Credit
Credit --> Audit
Audit --> Commit
If Audit fails
Everything rolls back.
Common Interview Questions
- What is a transaction?
- What are ACID properties?
- What does
@Transactionaldo? - Difference between flush and commit?
- What is rollback?
- What is transaction propagation?
- What are isolation levels?
- What happens when an exception occurs?
- What is a read-only transaction?
- How does Spring manage transactions?
Quick Revision
| Topic | Description |
|---|---|
| Transaction | Unit of work |
| ACID | Transaction guarantees |
| @Transactional | Transaction management |
| Commit | Permanent save |
| Rollback | Undo changes |
| Flush | Synchronize SQL |
| Propagation | Transaction behavior |
| Isolation | Concurrency control |
| ReadOnly | Query optimization |
| Persistence Context | Entity management |
Transaction Lifecycle
sequenceDiagram
Application->>Spring: Call Service
Spring->>Database: Begin Transaction
Spring->>EntityManager: Persistence Context
EntityManager->>Database: SQL
Database-->>Spring: Success
Spring->>Database: Commit
Spring-->>Application: Response
Production Scenario
Money Transfer Service
@Service
public class TransferService {
@Transactional
public void transfer(Long fromId,
Long toId,
BigDecimal amount) {
Account from = repository.findById(fromId).orElseThrow();
Account to = repository.findById(toId).orElseThrow();
from.debit(amount);
to.credit(amount);
transactionRepository.save(
new TransactionHistory(fromId, toId, amount)
);
}
}
If any step fails:
- Account debit is rolled back
- Account credit is rolled back
- Transaction history is rolled back
This guarantees atomicity.
Key Takeaways
- A transaction groups multiple database operations into a single unit of work.
- Transactions guarantee the ACID properties: Atomicity, Consistency, Isolation, and Durability.
- Spring Boot uses the
@Transactionalannotation to automatically manage transaction boundaries. - Commit permanently saves changes, while rollback discards all changes made during the transaction.
- Flush synchronizes the persistence context with the database but does not commit the transaction.
- The Persistence Context exists within a transaction and manages entity lifecycle, dirty checking, and the first-level cache.
- Propagation determines how nested transactions behave, while Isolation controls visibility between concurrent transactions.
- Use read-only transactions for query operations to improve performance.
- Keep transactions short, avoid long-running business logic and external API calls inside a transaction.
- Proper transaction management is essential for building reliable, scalable, and consistent enterprise applications.