定義及查詢一對一關係
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
兩個實體之間的「一對一關係」是指父系實體的每個例項都明確對應一個子實體的例項,反之亦然。
舉例來說,假設有一個音樂串流應用程式,使用者在其中擁有自己的媒體庫。每位使用者只有一個媒體庫,且每個媒體庫明確對應一位使用者。因此,User
實體和 Library
實體之間是一對一的關係。
請按照下列步驟,在資料庫中定義及查詢一對一關係:
- 定義關係:為兩個實體建立類別,確保一個實體參照另一個實體的主鍵。
- 查詢實體:在新資料類別中建立關係模型,並建立方法來擷取相關資料。
定義關係
如要定義一對一關係,請先為兩個實體建立類別。其中一個實體必須包含參照另一個實體主鍵的變數。
Kotlin
@Entity
data class User(
@PrimaryKey val userId: Long,
val name: String,
val age: Int
)
@Entity
data class Library(
@PrimaryKey val libraryId: Long,
val userOwnerId: Long
)
Java
@Entity
public class User {
@PrimaryKey public long userId;
public String name;
public int age;
}
@Entity
public class Library {
@PrimaryKey public long libraryId;
public long userOwnerId;
}
查詢實體
如要查詢使用者和對應媒體庫的清單,您必須先建立兩個實體之間的一對一關係模型。
如要這麼做,請建立新的資料類別,該類別的每個例項都含有父系實體例項,以及對應的子實體例項。在子實體的例項中加入 @Relation
註解,將 parentColumn
設為父系實體主鍵欄的名稱,然後再將 entityColumn
設為參照父系實體主鍵的子實體資料欄名稱。
Kotlin
data class UserAndLibrary(
@Embedded val user: User,
@Relation(
parentColumn = "userId",
entityColumn = "userOwnerId"
)
val library: Library
)
Java
public class UserAndLibrary {
@Embedded public User user;
@Relation(
parentColumn = "userId",
entityColumn = "userOwnerId"
)
public Library library;
}
最後,在 DAO 類別中新增方法,以傳回將父系實體和子實體配對的資料類別所有例項。此方法會要求 Room 執行兩項查詢。因此,您應將 @Transaction
註解新增至這個方法。這可確保整個作業以原子方式執行。
Kotlin
@Transaction
@Query("SELECT * FROM User")
fun getUsersAndLibraries(): List<UserAndLibrary>
Java
@Transaction
@Query("SELECT * FROM User")
public List<UserAndLibrary> getUsersAndLibraries();
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-07-27 (世界標準時間)。
[null,null,["上次更新時間:2025-07-27 (世界標準時間)。"],[],[],null,["# Define and query one-to-one relationships\n\nA *one-to-one relationship* between two entities is a relationship where each\ninstance of the parent entity corresponds to exactly one instance of the child\nentity, and the reverse is also true.\n\nFor example, consider a music streaming app where the user has a library of\nsongs that they own. Each user has only one library, and each library\ncorresponds to exactly one user. Therefore, there is a one-to-one relationship\nbetween the `User` entity and the `Library` entity.\n\nFollow these steps to define and query one-to-one relationships in your\ndatabase:\n\n1. **[Define the relationship](#define)**: Create classes for both entities, ensuring one references the other's primary key.\n2. **[Query the entities](#query)**: Model the relationship in a new data class and create a method to retrieve the related data.\n\nDefine the relationship\n-----------------------\n\nTo define a one-to-one relationship, first create a class for each of your two\nentities. One of the entities must include a variable that is a reference to the\nprimary key of the other entity. \n\n### Kotlin\n\n @Entity\n data class User(\n @PrimaryKey val userId: Long,\n val name: String,\n val age: Int\n )\n\n @Entity\n data class Library(\n @PrimaryKey val libraryId: Long,\n val userOwnerId: Long\n )\n\n### Java\n\n @Entity\n public class User {\n @PrimaryKey public long userId;\n public String name;\n public int age;\n }\n\n @Entity\n public class Library {\n @PrimaryKey public long libraryId;\n public long userOwnerId;\n }\n\nQuery the entities\n------------------\n\nTo query the list of users and corresponding libraries, you must first model the\none-to-one relationship between the two entities.\n\nTo do this, create a new data class where each instance holds an instance of the\nparent entity and the corresponding instance of the child entity. Add the\n[`@Relation`](/reference/kotlin/androidx/room/Relation) annotation to the instance of the child entity, with\n[`parentColumn`](/reference/kotlin/androidx/room/Relation#parentcolumn()) set to the name of the primary key column of the parent\nentity and [`entityColumn`](/reference/kotlin/androidx/room/Relation#entitycolumn()) set to the name of the column of the child entity\nthat references the parent entity's primary key. \n\n### Kotlin\n\n data class UserAndLibrary(\n @Embedded val user: User,\n @Relation(\n parentColumn = \"userId\",\n entityColumn = \"userOwnerId\"\n )\n val library: Library\n )\n\n### Java\n\n public class UserAndLibrary {\n @Embedded public User user;\n @Relation(\n parentColumn = \"userId\",\n entityColumn = \"userOwnerId\"\n )\n public Library library;\n }\n\nFinally, add a method to the DAO class that returns all instances of the data\nclass that pairs the parent entity and the child entity. This method requires\nRoom to run two queries. You should therefore add the [`@Transaction`](/reference/kotlin/androidx/room/Transaction)\nannotation to this method. This ensures that the whole operation runs\natomically. \n\n### Kotlin\n\n @Transaction\n @Query(\"SELECT * FROM User\")\n fun getUsersAndLibraries(): List\u003cUserAndLibrary\u003e\n\n### Java\n\n @Transaction\n @Query(\"SELECT * FROM User\")\n public List\u003cUserAndLibrary\u003e getUsersAndLibraries();"]]