Create a DAO Class
Kotlin and Android Development featuring Jetpack — by Michael Fazio (41 / 125)
👈 Add a RoomDatabase Class | TOC | Add Entity Classes 👉
As I mentioned before, we’re not going to be calling the PennyDropDatabase directly to get our data but will instead send everything through a DAO, or data access object. We mark an interface or abstract class as a DAO via the @Dao annotation. Most of the work with PennyDropDao will be handled by the Room library, leaving us to only worry about custom actions as needed. A majority of the functions in the DAO will be abstract with a particular annotation to give the function a purpose. If we need more control over what a function does, we can still write full SQL queries as well. In our case, we only need a single @Query function, with the other functions either using the @Insert or @Update annotations. The PennyDropDao abstract class with a couple of functions looks like this:
@Dao
abstract class PennyDropDao {
@Query("SELECT * FROM players WHERE playerName = :playerName")
abstract fun getPlayer(playerName: String): Player?
@Insert
abstract suspend fun insertGame(game: Game): Long
@Insert
abstract suspend fun insertPlayer(player: Player): Long
@Insert
abstract suspend fun insertPlayers(players: List<Player>): List<Long>
@Update
abstract suspend fun updateGame(game: Game)
}