Android Room@多对多关系?

我正在开发一个Android应用程序,正在使用Android操作系统中的新架构组件:LiveData、ViewModel和Room。 我对Room实现有一个小问题,那就是创建一个@Relationship,它返回连接查询(多对多关系)的结果。

我的数据库结构如下:

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

相关文章