gpt4 book ai didi

Android Room @Relation 多对多?

转载 作者:行者123 更新时间:2023-12-03 20:30:38 27 4
gpt4 key购买 nike

我正在开发一个安卓应用程序,并在安卓操作系统中使用新的架构组件:LiveData、ViewModel 和 Room。
我对 Room 实现有一个小问题,即创建一个 @Relation,它从 JOIN 查询(​​多对多关系)返回结果。

我的数据库结构如下所示:

@Entity
public class Student{
@PrimaryKey
private int id;
private String name;
private String email;
}

@Entity
public class Group{
@PrimaryKey
private int id;
private String name;
}

@Entity(foreignKeys = {
@ForeignKey(entity = Student.class,
parentColumns = "id",
childColumns = "student_id"),
@ForeignKey(entity = Group.class,
parentColumns = "id",
childColumns = "group_id")
})
public class StudentGroup{

private int studentId;
private int groupId;
}

我如何才能获得仅针对特定学生的所有组,像这样?
public class StudentWithGroups{
@Relation(parentColumn = "id", entityColumn = "rule_id", entity =
StudentGroup.class)
private List<Group> groups;
}

我已经检查了 How can I represent a many to many relation with Android Room? 之类的问题和 Android Persistence room: "Cannot figure out how to read this field from a cursor"

最佳答案

带介绍Junction在房间里你可以轻松处理多对多的关系。

修改学生表和组表的主键为:

@Entity
public class Student{
@PrimaryKey
private int sId;
private String name;
private String email;
}

@Entity
public class Group{
@PrimaryKey
private int gId;
private String name;
}

@Entity(foreignKeys = {
@ForeignKey(entity = Student.class,
parentColumns = "sId",
childColumns = "studentId"),
@ForeignKey(entity = Group.class,
parentColumns = "gId",
childColumns = "groupId")
})
public class StudentGroup{
private int studentId;
private int groupId;
}

您可以获得所有特定学生组:
 public class StudentWithGroups{
@Embedded
Student student;
@Relation(
parentColumn = "sId",
entity = Group.class,
entityColumn = "gId",
associateBy = @Junction(
value = StudentGroup.class,
parentColumn = "studentId",
entityColumn = "groupId)
)
List<Group> groups;
}

现在您可以查询数据库以获取结果:
 @Dao
public interface StudentDao {
@Query("SELECT * FROM Student")
List<StudentWithGroups> getGroupsOfStudent();
}

关于Android Room @Relation 多对多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48640803/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com