为了解决Android Room中复杂数据中的多对多关系(IDs),需要进行以下步骤:
@Entity(tableName = "teacher_student_join", primaryKeys = {"teacherId", "studentId"}) public class TeacherStudentJoin { public int teacherId; public int studentId; public String className;
public TeacherStudentJoin(int teacherId, int studentId, String className) {
this.teacherId = teacherId;
this.studentId = studentId;
this.className = className;
}
}
@Entity(tableName = "teacher_table")
public class Teacher {
@PrimaryKey
public int id;
public String name;
public List
public Teacher(int id, String name, List students) {
this.id = id;
this.name = name;
this.students = students;
}
}
@Entity(tableName = "student_table")
public class Student {
@PrimaryKey
public int id;
public String name;
public List
public Student(int id, String name, List teachers) {
this.id = id;
this.name = name;
this.teachers = teachers;
}
}
@Dao public interface TeacherStudentDao { @Insert(onConflict = OnConflictStrategy.REPLACE) void insert(TeacherStudentJoin teacherStudentJoin);
@Transaction
@Query("SELECT * FROM teacher_table")
List getTeacherWithStudents();
@Transaction
@Query("SELECT * FROM student_table WHERE id=:studentId")
List getStudentWithTeachers(int studentId);
}
public class TeacherWithStudents { @Embedded public Teacher teacher; @Relation( parent