Middle
What is a transaction? Tell about isolation levels and anomalies.
sobes.tech AI
Answer from AI
A transaction is a sequence of database operations executed as a single unit: either all operations successfully complete (commit), or in case of an error, all changes are rolled back (rollback).
Transaction isolation levels determine how much one transaction can see the changes made by other concurrent transactions. The main isolation levels:
- Read Uncommitted — a transaction can see uncommitted changes of other transactions (dirty read).
- Read Committed — a transaction only sees committed changes, but non-repeatable reads are possible.
- Repeatable Read — guarantees that repeated reads of the same data within a transaction will yield the same result, but phantom reads are possible.
- Serializable — the strictest level, transactions are executed as if sequential, preventing all anomalies.
Typical anomalies:
- Dirty Read — reading uncommitted data from another transaction.
- Non-repeatable Read — data changes between two reads within the same transaction.
- Phantom Read — new rows added by another transaction appear in subsequent queries.
In Java, transaction management is often handled using JDBC API or frameworks (Spring), where you can set the isolation level and control the atomicity of operations.