创建数据库视图

2.1.0 及更高版本的Room 持久性库支持SQLite 数据库视图,允许您将查询封装到一个类中。Room 将这些基于查询的类称为视图,它们在DAO中使用时与简单数据对象的行为相同。

创建视图

要创建视图,请将@DatabaseView注释添加到类中。将注释的值设置为该类应表示的查询。

以下代码片段提供了一个视图示例

Kotlin

@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?
)

Java

@DatabaseView("SELECT user.id, user.name, user.departmentId," +
              "department.name AS departmentName FROM user " +
              "INNER JOIN department ON user.departmentId = department.id")
public class UserDetail {
    public long id;
    public String name;
    public long departmentId;
    public String departmentName;
}

将视图与您的数据库关联

要在您的应用数据库中包含此视图,请在应用的@Database注释中包含views属性

Kotlin

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

Java

@Database(entities = {User.class}, views = {UserDetail.class},
          version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}