Android Room@多对多关系? [英] Android Room @Relation many-to-many?

查看:0
本文介绍了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();
}

这篇关于Android Room@多对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆