在資料庫中建立檢視表

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;
}

將檢視表與資料庫建立關聯

如要在應用程式的資料庫中加入這個檢視表,請將 views 屬性加入應用程式的 @Database 註解中:

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();
}