Create views into a database

The Room persistence library supports SQLite database views, which let you encapsulate a query in a class. Room refers to these query-backed classes as views, and you can use them as data objects in a data access object (DAO).

Create a view

To create a view, add the @DatabaseView annotation to a class. Set the annotation value to the query that the class represents.

The following code snippet provides an example of a view:

@DatabaseView(
    """
    SELECT User.id, User.name, User.departmentId, Department.name AS departmentName
    FROM User INNER JOIN Department ON User.departmentId = Department.id
    """
)
data class UserDetail(
    val id: Long,
    val name: String?,
    val departmentId: Long,
    val departmentName: String?
)

Associate a view with your database

To include this view in your database, add the views property to your app's @Database annotation:

@Database(
    entities = [User::class, Department::class],
    views = [UserDetail::class],
    version = 1
)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}