In Room, what does @Transaction do on a DAO function with a body, and on which DAO functions is it pointless?
answer
- several DAO calls, one commit
- generated override wraps your body
- an escaping exception rolls back
- shortcuts are already transactional
- no async return types
basics
~20 sOn a DAO function with a body, @Transaction runs the whole body in one database transaction, committed unless an exception escapes. On @Insert, @Update, @Delete and write @Query functions it adds nothing: each already runs in a transaction.
solid answer
~40 sPut `@Transaction` on a non-abstract function of an abstract `@Dao` class, and Room's generated subclass runs your body inside one database transaction, keeping parameters and return type. It is marked successful unless an exception is thrown out of the body, so `archiveTag(tag)` followed by `deleteArchived()` either both commit or both roll back. The annotation is pointless on `@Insert`, `@Update`, `@Delete`, and on `@Query` functions running `INSERT`, `UPDATE` or `DELETE`, because Room already wraps each of those in a transaction. On a `SELECT` it makes a large result or a relation read consistent. Two traps: catching an exception inside the body commits the partial work, and Room 2.x rejects a wrapper that returns an async type such as `LiveData` or `Flow`. In Room 3.0 the wrapper is a `suspend` function.
code
kotlin · 22 linesimport androidx.room3.Dao
import androidx.room3.Insert
import androidx.room3.Query
import androidx.room3.Transaction
@Dao
abstract class NoteArchiveDao {
@Query("UPDATE notes SET archived = 1 WHERE tag = :tag")
abstract suspend fun archiveTag(tag: String): Int
@Query("DELETE FROM notes WHERE archived = 1")
abstract suspend fun deleteArchived(): Int
@Insert
abstract suspend fun insert(note: Note): Long
@Transaction
open suspend fun archiveAndPurge(tag: String): Int {
archiveTag(tag)
return deleteArchived()
}
}go deeper
Recall that @Transaction on a DAO function with a body runs all its calls in one transaction, committed only if no exception escapes.
Explain why it is redundant on shortcut and write @Query functions, why it helps relation and large SELECT reads, and what Room generates.
Catch the production traps: swallowed exceptions committing partial work, network calls holding the single writer, and rejected async return types.
Set a team rule that transaction bodies contain only database calls and stay short, since one slow body stalls every write in the app.
## The problem it solves Each DAO call is its own unit of work. If a notes app archives every note with a tag and then purges archived notes as two separate calls, a crash or a thrown exception between them leaves the database half-done, and another write can slip in between. `@Transaction` groups several DAO calls so they **commit together or not at all**. ## How a transaction function works Declare a function **with a body** in an abstract `@Dao` class and annotate it `@Transaction`: ```kotlin @Transaction open suspend fun archiveAndPurge(tag: String): Int { archiveTag(tag) return deleteArchived() } ``` Room generates a subclass whose override begins a transaction, calls your implementation, and ends it. The contract: 1. All parameters and the return type are preserved. 2. The transaction is marked **successful unless an exception is thrown** in the function body. 3. If an exception escapes, the transaction rolls back and the exception propagates to the caller. Room's release notes also cover a Kotlin interface function with a body annotated this way, but the abstract class is the documented shape. ## Where it is pointless | DAO function | Effect of `@Transaction` | |---|---| | `@Insert`, `@Update`, `@Delete` | none: each call already runs in a transaction | | `@Query` running `INSERT`, `UPDATE` or `DELETE` | none: Room wraps write statements automatically | | `@Query` running a `SELECT` | the read runs in a transaction | | non-abstract function with a body | the whole body runs in one transaction | A `SELECT` gains from it in two documented cases: a result object with `@Relation` properties, which Room loads with extra queries that must see the same data (covered with Room's relations), and a result too large for one Android `CursorWindow`, where a concurrent change between window swaps could otherwise corrupt the result. In Room 3.0 that second case depends on the driver: it applies to a driver over Android's SQLite bindings. ## The traps - **Swallowed exceptions commit.** If the body catches the exception from its second call and returns normally, no exception escaped, so the first call's changes are committed. Let failures propagate, or rethrow. - **Async return types are rejected.** In Room 2.x (since 2.1) a non-abstract `@Transaction` function may not return an async type such as `LiveData`, RxJava's `Single` or `ListenableFuture`, and Room also reports an error for a `Flow` return: work that runs later on another thread cannot be held inside the transaction. - **Long work holds the writer.** Room performs at most one write transaction at a time and queues the rest first come, first served. A network call or heavy computation inside the body stalls every other write in the app until it finishes, so fetch first and then write in a short transaction. - **Calls outside the body are not included.** Only the DAO calls made while the body runs are inside the transaction; a write the caller makes afterwards is a separate unit, so put every write that must agree inside the one function. ## In Room 3.0 DAO functions with plain return types must be `suspend` in Room 3.0, and that includes transaction wrappers. Two patch releases fixed wrapper bugs: 3.0.2 a deadlock when a wrapper switched coroutine context with `AndroidSQLiteDriver` configured, and 3.0.3 an `IllegalMonitorStateException` regression in wrappers. Because Room 3.0 has no blocking DAO functions, the Room 2.x pattern of a blocking `@Transaction fun` called from a background thread has no direct equivalent: callers launch a coroutine and call the suspend wrapper. Running a transaction from outside a DAO, with `withWriteTransaction` and its relatives, is covered with Room's coroutine support. ## When to reach for it - Two or more writes that must agree: archive then purge, move a note between folders, replace a set of rows. - A read-modify-write on one row where a concurrent writer could interleave. - A read assembled from several queries that must see one snapshot. Replacing a tag's notes shows why the wrapper matters. As two separate calls, delete-then-insert commits an empty tag in between, and a screen observing that tag can briefly render nothing. Inside one `@Transaction` function the delete and the insert commit together, so no reader ever sees the gap. Keep the body to database calls, keep it short, and let exceptions out.
- A @Transaction function calls a REST API between two writes; what goes wrong?The transaction stays open for the whole network round trip. Room runs one write transaction at a time and queues others, so every other write in the app waits behind a slow or hanging request. Fetch the data first, then open a short transaction that only writes.
- Why does putting @Transaction on an @Insert function not make a batch of inserts atomic across two calls?Each `@Insert` call already runs in its own transaction, so the annotation adds nothing, and two separate calls remain two transactions. To make them atomic, pass all entities to one `@Insert` call, or call both inside one `@Transaction` function with a body.
- @Transaction on an @Insert function makes its inserts atomic with the caller's next write.
- Catching an exception inside a @Transaction body still rolls everything back.
- A @Transaction wrapper can return LiveData so the transaction spans each emission.
- Room runs several write transactions in parallel, so long bodies are harmless.
- Every @Query needs @Transaction to be safe.
Assumes Room 3.0.3, where @Transaction wrappers are suspend functions; 3.0.2 fixed a deadlock in wrappers that switch context on AndroidSQLiteDriver and 3.0.3 an IllegalMonitorStateException regression.