创建数据库视图

Room 持久性库 的 2.1.0 及更高版本提供对 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();
}