Android Room @Relation多对多?

时间:2018-02-06 10:30:21

标签: android many-to-many android-room android-livedata

我正在开发一个Android应用程序,并且正在使用Android操作系统中的新架构组件:LiveData,ViewModel和Room。 关于创建@Relation的Room实现我遇到一个小问题,它返回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"

等问题

2 个答案:

答案 0 :(得分:2)

通过介绍室内Junction,您可以轻松处理多对多关系。

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

<input onChange={(event) => this.inputChangeHandler(1,event)} value={this.state.value} />

您可以将特定学生的所有组都设置为:

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

答案 1 :(得分:1)

  

我如何只针对特定学生获得所有小组,类似的东西?

this sample code中,我有:

  @Query("SELECT categories.* FROM categories\n"+
    "INNER JOIN customer_category_join ON categories.id=customer_category_join.categoryId\n"+
    "WHERE customer_category_join.customerId=:customerId")
List<Category> categoriesForCustomer(String customerId);

将其翻译成您的实体会产生类似的结果:

  @Query("SELECT Group.* FROM Group\n"+
    "INNER JOIN StudentGroup ON Group.id=StudentGroup.groupId\n"+
    "WHERE StudentGroup.studentId=:studentId")
List<Group> groupsForStudent(String studentId);

通常,使用Room,找出SQL忽略Room,然后在DAO中使用该SQL。