A database table does not do much good if you cannot edit or access its contents. The first step to interacting with your database tables is to create a data access object, or DAO. A DAO is an interface that contains functions for each database operation you want to perform. In this chapter, CriminalIntent’s DAO needs two query functions: one to return a list of all crimes in the database and another to return a single crime matching a given UUID.
Add a file named CrimeDao.kt to the database package.
In it, define an empty interface named CrimeDao annotated with Room’s @Dao
annotation.
The @Dao
annotation lets Room know that CrimeDao is one of your data access objects.
When you hook CrimeDao up to your database class, Room will generate implementations of the functions you add to this interface.
Speaking of adding functions, now is the time. Add two query functions to CrimeDao.
Listing 11.7 Adding database query functions (database/CrimeDao.kt
)
@Dao interface CrimeDao { @Query("SELECT * FROM crime") fun getCrimes(): List<Crime> @Query("SELECT * FROM crime WHERE id=(:id)") fun getCrime(id: UUID): Crime? }
The @Query
annotation indicates that getCrimes() and getCrime(UUID) are meant to pull information out of the database, rather than inserting, updating, or deleting items from the database.
The return type of each query function in the DAO interface reflects the type of result the query will return.
The @Query
annotation expects a string containing a SQL command as input.
In most cases you only need to know minimal SQL to use Room, but if you are interested in learning more check out the SQL Syntax section at www.sqlite.org.
SELECT * FROM crime
asks Room to pull all columns for all rows in the crime
database table.
SELECT * FROM crime WHERE id=(:id)
asks Room to pull all columns from only the row whose id
matches the ID value provided.
With that, the CrimeDao is complete, at least for now. In Chapter 12 you will add a function to update an existing crime. In Chapter 14 you will add a function to insert a new crime.
Next, you need to register your DAO class with your database class. Since the CrimeDao is an interface, Room will handle generating the concrete version of the class for you. But for that to work, you need to tell your database class to generate an instance of the DAO.
To hook up your DAO, open CrimeDatabase.kt and add an abstract function that has CrimeDao as the return type.
Listing 11.8 Registering the DAO in the database (database/CrimeDatabase.kt
)
@Database(entities = [ Crime::class ], version=1) @TypeConverters(CrimeTypeConverters::class) abstract class CrimeDatabase : RoomDatabase() { abstract fun crimeDao(): CrimeDao }
Now, when the database is created, Room will generate a concrete implementation of the DAO that you can access. Once you have a reference to the DAO, you can call any of the functions defined on it to interact with your database.
3.137.187.233