1 対多のリレーションを定義してクエリを実行する
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
2 つのエンティティ間の 1 対多のリレーションとは、親エンティティの各インスタンスが子エンティティの 0 個以上のインスタンスに対応し、子エンティティの各インスタンスは親エンティティの 1 つのインスタンスにだけ対応するリレーションです。
音楽ストリーミング アプリで、ユーザーがプレイリストに曲を整理できる機能があるとします。各ユーザーが作成できるプレイリストの数に制限はありませんが、各プレイリストの作成者は 1 人だけです。したがって、User
エンティティと Playlist
エンティティの間には 1 対多のリレーションがあります。
データベースで 1 対多のリレーションを定義してクエリを実行する手順は次のとおりです。
- 関係を定義する: 両方のエンティティのクラスを作成し、子エンティティが親の主キーを参照するようにします。
- エンティティをクエリする: 新しいデータクラスでリレーションをモデル化し、関連データを取得するメソッドを実装します。
関係を定義する
1 対多のリレーションを定義するには、まず 2 つのエンティティのクラスを作成します。1 対 1 のリレーションと同様に、子エンティティには、親エンティティの主キーへの参照である変数を含める必要があります。
Kotlin
@Entity
data class User(
@PrimaryKey val userId: Long,
val name: String,
val age: Int
)
@Entity
data class Playlist(
@PrimaryKey val playlistId: Long,
val userCreatorId: Long,
val playlistName: String
)
Java
@Entity
public class User {
@PrimaryKey public long userId;
public String name;
public int age;
}
@Entity
public class Playlist {
@PrimaryKey public long playlistId;
public long userCreatorId;
public String playlistName;
}
エンティティをクエリする
ユーザーと対応するプレイリストのリストをクエリするには、最初に 2 つのエンティティ間の 1 対多のリレーションをモデル化する必要があります。
そのために、各インスタンスが親エンティティのインスタンスと、対応する子エンティティのインスタンスのリストを保持する、新しいデータクラスを作成します。@Relation
アノテーションを子エンティティのインスタンスに追加します。このとき、parentColumn
を親エンティティの主キー列の名前に設定し、entityColumn
を親エンティティの主キーを参照する子エンティティの列の名前に設定します。
Kotlin
data class UserWithPlaylists(
@Embedded val user: User,
@Relation(
parentColumn = "userId",
entityColumn = "userCreatorId"
)
val playlists: List<Playlist>
)
Java
public class UserWithPlaylists {
@Embedded public User user;
@Relation(
parentColumn = "userId",
entityColumn = "userCreatorId"
)
public List<Playlist> playlists;
}
最後に、親エンティティと子エンティティをペアにするデータクラスのすべてのインスタンスを返すメソッドを DAO クラスに追加します。このメソッドでは Room に 2 つのクエリを実行させる必要があるため、@Transaction
アノテーションを追加して、操作全体がアトミックに実行されるようにします。
Kotlin
@Transaction
@Query("SELECT * FROM User")
fun getUsersWithPlaylists(): List<UserWithPlaylists>
Java
@Transaction
@Query("SELECT * FROM User")
public List<UserWithPlaylists> getUsersWithPlaylists();
このページのコンテンツやコードサンプルは、コンテンツ ライセンスに記載のライセンスに従います。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-many relationships\n\nA *one-to-many relationship* between two entities is a relationship where each\ninstance of the parent entity corresponds to zero or more instances of the child\nentity, but each instance of the child entity can only correspond to exactly one\ninstance of the parent entity.\n\nIn the music streaming app example, suppose the user has the ability to organize\ntheir songs into playlists. Each user can create as many playlists as they want,\nbut exactly one user creates each playlist. Therefore, there is a one-to-many\nrelationship between the `User` entity and the `Playlist` entity.\n\nFollow these steps to define and query one-to-many relationships in your\ndatabase:\n\n1. **[Define the relationship](#define)**: Create classes for both entities, with the child entity referencing the parent's primary key.\n2. **[Query the entities](#query)**: Model the relationship in a new data class and implement a method to retrieve the related data.\n\nDefine the relationship\n-----------------------\n\nTo define a one-to-many relationship, first create a class for the two entities.\nAs in a one-to-one relationship, the child entity must include a variable that\nis a reference to the primary key of the parent 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 Playlist(\n @PrimaryKey val playlistId: Long,\n val userCreatorId: Long,\n val playlistName: String\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 Playlist {\n @PrimaryKey public long playlistId;\n public long userCreatorId;\n public String playlistName;\n }\n\nQuery the entities\n------------------\n\nTo query the list of users and corresponding playlists, you must first model the\none-to-many 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 a list of all corresponding child entity instances. 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 UserWithPlaylists(\n @Embedded val user: User,\n @Relation(\n parentColumn = \"userId\",\n entityColumn = \"userCreatorId\"\n )\n val playlists: List\u003cPlaylist\u003e\n )\n\n### Java\n\n public class UserWithPlaylists {\n @Embedded public User user;\n @Relation(\n parentColumn = \"userId\",\n entityColumn = \"userCreatorId\"\n )\n public List\u003cPlaylist\u003e playlists;\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, so add the [`@Transaction`](/reference/kotlin/androidx/room/Transaction) annotation to this\nmethod so that the whole operation is performed atomically. \n\n### Kotlin\n\n @Transaction\n @Query(\"SELECT * FROM User\")\n fun getUsersWithPlaylists(): List\u003cUserWithPlaylists\u003e\n\n### Java\n\n @Transaction\n @Query(\"SELECT * FROM User\")\n public List\u003cUserWithPlaylists\u003e getUsersWithPlaylists();"]]