我是Room的新手,我在玩一个示例应用程序,它可以注册学生并在RecyclerView中显示他们。
我有一个学生类,类似于
@Entity
public class Student {
@PrimaryKey (autoGenerate = true)
private int id;
private String studentNumber;
private String name;
private int schoolId;
}
一个学校类。
@Entity
public class School {
@PrimaryKey (autoGenerate = true)
private int id;
private String name;
}
有一个一对多的关系(一个学校有一个学生列表,一个学生属于一个学校)。
public class SchoolWithStudents {
@Embedded private School school;
@Relation(
parentColumn = "id",
entityColumn = "schoolId"
)
private List<Student> studentList;
}
如果我有一个活动,我想显示学生的详细信息,包括学校名称。我觉得很奇怪,我必须查询数据库才能得到学校名称,就像getSchoolById那样。
我来自Spring Boot,在Spring Boot中,在Student类中嵌入一个学校对象并管理关系是非常正常的。
所以获取学校名称就像:student.getSchool.getName().我没看错吧?我真的需要额外的查询吗?我还没有用SchoolWithStudents做什么,只是为了架构而声明的
我觉得很奇怪,我必须查询数据库才能得到学校的名字,就像getSchoolById一样
你不必这样做。在任何情况下,只要打一个电话给Room,就能得到你想要的所有数据。
如果你进行下一次调用,
@Query("SELECT * from school")
List<SchoolWithStudents> loadSchoolWithStudents();
你就会得到一个嵌入的列表 School
对象,所以不需要额外的查询--你的响应中包含了学校的名称和所有属性(而不是在 Student
对象,但无论如何,你可以很容易地从 School
含有 school.getName()
).
如果你想用另一种结构得到列表--------。StudentWithSchool
其中Student和School都会 "同级"),可以用。
public class StudentWithSchool {
@Embedded private Student student;
@Relation(
parentColumn = "schoolId",
entityColumn = "id"
)
private School school;
}
和查询方法。
@Query("SELECT * from student")
List<StudentWithSchool> loadStudentWithSchool();