Room 2.1.0 and later provides support for database views, allowing queries to be encapsulated in a class. Room calls these query-enabled classes views and uses them like normal data objects in daOs.
Note: Just like any other entity, you can run a SELECT statement on a view. However, you cannot run INSERT,UPDATE, and DELETE statements on views
Create a view
To create a view, add the @databaseView annotation to the class and set the annotation value to the corresponding query statement for the 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? )Copy the code
Associate a view with a database
To make the view part of your app’s Database, you need to set the views attribute of the @Database annotation
@Database(entities = arrayOf(User::class),
views = arrayOf(UserDetail::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
Copy the code
0. Overview
1. Use Room entities to define data
2. Define relationships between objects
3. Create a view in the database
4. Use Room DAOs to access data
5. Migrate the database
6. Test the database
7. Reference complex data using Room