5.5 Data Access Objects

When you use the Room persistence library to store your app's data, you interact with the stored data by defining data access objects, or DAOs. Each DAO includes methods that offer abstract access to your app's database.

Anatomy of a DAO

You can define each DAO as either an interface or an abstract class. For basic use cases, you should usually use an interface. In either case, you must always annotate your DAOs with @Dao. DAOs don't have properties, but they do define one or more methods for interacting with the data in your app's database.

Here is an example DAO for our grocery item entity:

@Dao
interface GroceryItemDao {
    // Get all GroceryItemEntitys
    @Query("SELECT * FROM groceryitementity")
    fun getAll(): List<GroceryItemEntity> 

    // Get all GroceryItemEntitys who's name is in the list `items`
    @Query("SELECT * FROM groceryitementity WHERE item IN (:items)")
    fun loadAllByIds(items: List<String>): List<GroceryItemEntity>

    // Insert the given GroceryItemEntity
    @Insert
    fun insertAll(vararg users: GroceryItemEntity)
    
    // Update the GroceryItemEntity given. Uses the primary key to match up the Entity
    @Update
    fun update(groceryItem: GroceryItemEntity)

    // Delete the given GroceryItemEntity by the primary key
    @Delete
    fun delete(groceryItem: GroceryItemEntity)
}

Note: Since primary keys must be unique to update an item that already exists in the database, you must use an update method, not an insert method. It will throw an exception if an insert is called with a primary key that already exists in the database.

Last updated