Room DAO: Your App's Type-Safe SQL Interface

A Room DAO is an interface that translates your method calls into SQL queries. It's how your Android app's code talks to its local database without writing boilerplate. The footgun is putting business logic in a DAO; it should only access data.
WHY IT EXISTS Before Room, Android developers manually wrote SQL, managed SQLiteOpenHelper, and parsed Cursor objects. This was verbose and error-prone; a typo in a SQL string would crash the app at runtime. Room, with its DAOs, was created to provide a type-safe, compile-time verified abstraction layer over SQLite, making database operations robust and easier to write.
THE MENTAL MODEL A DAO (Data Access Object) is your database's API. Instead of writing SELECT * FROM users WHERE id = ?, you define an interface with a method like fun getUser(id: Int): User. You annotate this method, and Room generates the necessary code to execute the SQL, handle parameters, and map the result into your User object. It's a contract that separates your application logic from the nitty-gritty of database interaction.
HOW IT WORKS You define a DAO as a Kotlin interface or an abstract Java class and annotate it with @Dao. Inside, you declare methods for each database operation using annotations like @Insert, @Update, @Delete, and @Query. For @Query, you provide the SQL string. At compile time, Room's annotation processor validates your SQL against your database schema (your @Entity classes) and generates the concrete implementation. This means a bad query or a typo in a column name will cause a compile error, not a runtime crash.
WHEN TO USE IT You use a DAO whenever you need to interact with a Room database. It is the required and standard way to define data operations for Room. Every @Entity (table) you create will typically have a corresponding DAO to manage its data via create, read, update, and delete (CRUD) operations.
WHEN NOT TO USE IT Do not place business logic, data transformations, or logic for combining data from multiple sources (like a network call and the database) inside a DAO. A DAO's responsibility is strictly to access one data source: the database. For more complex logic, use a Repository pattern that uses one or more DAOs but isn't a DAO itself.
ONE CANONICAL EXAMPLE For a User data class marked as an @Entity, a simple DAO would look like this in Kotlin: @Dao interface UserDao { @Query("SELECT * FROM users") fun getAll(): List<User>
@Insert suspend fun insert(user: User)
@Delete suspend fun delete(user: User) } Here, getAll() fetches all users, while insert() and delete() are suspend functions, telling Room to make them main-safe so they don't block the UI thread.
Read the original → developer.android.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.