Transactions
an5 ORM supports transactions to ensure data consistency when performing multiple related operations.
Postgresql note:
PostgreSQL uses standard ACID transactions with BEGIN, COMMIT, and ROLLBACK. Nested transactions leverage SAVEPOINT.
Basic Transaction (Scoped)
An5DbContext.transaction commits when the callback returns and rolls back when it
throws:
User user = db.transaction(tx -> {
User created = db.getUser().create(
new User().withEmail("john@example.com").withName("John"));
db.getOrder().create(
new Order().withUserId(created.getId()).withTotal(100));
return created;
});
The work runs on the context’s adapter, so the typed handles take part in the same
transaction; tx is that adapter again when you need raw SQL. Nested transaction()
calls are rejected rather than flattened, because an inner commit would turn an outer
rollback into a partial save.
Error Handling and Rollback
try {
db.transaction(tx -> {
db.getUser().create(new User().withEmail("john@example.com").withName("First"));
throw new IllegalStateException("rollback");
});
} catch (IllegalStateException expected) {
// the insert above was discarded with the transaction
} catch (SQLException error) {
// connection-level failure
}
Best Practices
- Keep transactions short - Minimize the time table rows are locked to avoid blocking concurrent queries.
- Handle errors properly - Always handle potential deadlock or timeout exceptions in application code.
- Consistent ordering - Always update tables and records in a deterministic order across all endpoints to prevent database deadlocks.
- Choose the appropriate isolation level - Tailor the transaction isolation according to concurrency and consistency requirements.
Next Steps
- Advanced Queries - Filter, sort, and paginate data
- Relations & Joins - Model relational data integrity