1 対 1 のリレーションを定義してクエリを実行する
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
2 つのエンティティ間の 1 対 1 のリレーションとは、親エンティティの各インスタンスが子エンティティの 1 つのインスタンスに対応するリレーション、あるいはその逆のリレーションです。
たとえば、音楽ストリーミング アプリで、ユーザーが自分の所有する曲のライブラリを持っている場合を考えてみましょう。各ユーザーはライブラリを 1 つだけ持ち、各ライブラリは 1 人のユーザーに対応しています。したがって、User
エンティティと Library
エンティティの間には 1 対 1 のリレーションがあります。
データベースで 1 対 1 の関係を定義してクエリを実行する手順は次のとおりです。
- リレーションを定義する: 両方のエンティティのクラスを作成し、一方がもう一方の主キーを参照するようにします。
- エンティティをクエリする: 新しいデータクラスで関係をモデル化し、関連データを取得するメソッドを作成します。
関係を定義する
1 対 1 のリレーションを定義するには、まず 2 つのエンティティにそれぞれクラスを作成します。一方のエンティティには、他方のエンティティの主キーへの参照である変数を含める必要があります。
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;
}
エンティティをクエリする
ユーザーと対応するライブラリのリストをクエリするには、最初に 2 つのエンティティ間の 1 対 1 のリレーションをモデル化する必要があります。
このために、親エンティティのインスタンスと子エンティティの対応するインスタンスを保持する新しいデータクラスを作成します。@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 に 2 つのクエリを実行させる必要があります。したがって、このメソッドに @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 UTC。
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["必要な情報がない","missingTheInformationINeed","thumb-down"],["複雑すぎる / 手順が多すぎる","tooComplicatedTooManySteps","thumb-down"],["最新ではない","outOfDate","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["サンプル / コードに問題がある","samplesCodeIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2025-07-27 UTC。"],[],[],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();"]]