Android房间一对多关系

Android room one to many relationship(Android房间一对多关系)

本文介绍了Android房间一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一对多关系,我联机查看了多篇文章和教程,但所有示例都显示一个表与另一个表具有一对多关系。

在我的要求中,我有两个表与另一个表具有一对多关系(请查看下图)

学生表有来自班级和学校表的FK。大多数示例都说明了班级与学生或学校与学生之间的一对多关系。

我想做[班级,学校]-学生。

核心数据会在iOS上处理,但我无法在Android上解决这个问题。我尝试了Android文档中显示的嵌套关系示例,但不起作用。

推荐答案

您的问题未清楚说明。但是,以下是一个实际示例,它演示了基于您的架构提取关系的两种方法。

  • 注意:将Class用作类充满了潜在问题,不推荐使用。但是,以下代码确实使用了类,并且为了规避某些问题,可能无法完全反映您的架构。

示例代码

学校实体:-

@Entity(tableName = "_school")
class School {
    @PrimaryKey
    @ColumnInfo(name = "school_id")
    Long Schoolid;
    @NonNull
    @ColumnInfo(name = "school_name")
    String SchoolName;

    School(){}

    @Ignore
    School(String schoolName) {
        this.SchoolName = schoolName;
    }
}

(不明智的名称选择):-

@Entity(tableName = "_class")
class Class {
    @PrimaryKey
    @ColumnInfo(name = "class_id")
    Long ClassId;
    @NonNull
    @ColumnInfo(name = "class_name")
    String ClassName;

    Class(){}

    @Ignore
    Class(String className) {
        this.ClassName = className;
    }
}

学生实体(包括外键约束):-

@Entity(
        tableName = "_student", foreignKeys = {
        @ForeignKey(
                entity = School.class,
                parentColumns = {"school_id"},
                childColumns = {"school_id"},
                onDelete = ForeignKey.CASCADE,
                onUpdate = ForeignKey.CASCADE
        ),
        @ForeignKey(
                entity = Class.class,
                parentColumns = {"class_id"},
                childColumns = {"class_id"},
                onDelete = ForeignKey.CASCADE,
                onUpdate = ForeignKey.CASCADE
        )
        }
)
class Student {
    @PrimaryKey
    @ColumnInfo(name = "student_id")
    Long StudentId;
    @ColumnInfo(name = "Student_name")
    String StudentName;
    @ColumnInfo(name = "school_id", index = true)
    Long SchoolId;
    @ColumnInfo(name = "class_id", index = true)
    Long ClassId;

    Student(){}

    @Ignore
    Student(String studentName, long schoolId, long classId) {
        this.StudentName = studentName;
        this.SchoolId = schoolId;
        this.ClassId = classId;
    }
}

POJO方法1-类StudentAndSchoolAndClass-(不使用@Relation)

class StudentAndSchoolAndClass {

    @Embedded
    Student student;
    String school_name;
    String class_name;
}

POJO方法2-ClassStudentWithSchoolWithClass-(使用@Relation的)

class StudentWithSchoolWithClass {

    @Embedded
    Student student;

    @Relation(entity = School.class,parentColumn = "school_id", entityColumn = "school_id")
    List<School> schoolList;
    @Relation(entity = Class.class,parentColumn = "class_id",entityColumn = "class_id")
    List<Class> classList;
}

DAO接口全部DAO

@Dao
interface AllDao {

    @Insert
    Long insertSchool(School s);
    @Insert
    Long insertClass(Class c);
    @Insert
    Long insertStudent(Student s);
    @Query("SELECT * FROM _school")
    List<School> getAllSchools();
    @Query("SELECT * FROM _school WHERE school_id = :school_id ")
    School getSchoolById(Long school_id);
    @Query("SELECT * FROM _class")
    List<Class> getAllClasses();
    @Query("SELECT * FROM _class WHERE class_id = :class_id")
    Class getClassById(Long class_id);
    @Query("SELECT * FROM _student JOIN _school ON _school.school_id = _student.school_id JOIN _class ON _class.class_id = _student.class_id")
    List<StudentAndSchoolAndClass> getStudentAndSchoolAndClass();
    @Query("SELECT * FROM _student")
    List<StudentWithSchoolWithClass> getStudentWithSchoolWithClass();

}
  • 注意最后两个查询使用各自的POJO,特别是
  • 具有@Relations的PJO具有通过联接的
  • 定义的关系

@Database类MyDatabase

@Database(entities = {School.class,Class.class,Student.class},version = 1)
abstract class MyDatabase extends RoomDatabase {
    abstract AllDao allDao();
}

最后一个活动MainActivity,该活动将一些数据加载到数据库中,然后使用2@查询和相应的POJO类提取一些数据。

public class MainActivity extends AppCompatActivity {

    MyDatabase db;
    AllDao allDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Build the MyDatabase instance
        db = Room.databaseBuilder(this,MyDatabase.class,"mydb")
                .allowMainThreadQueries()
                .build();
        // Build the allDao instance
        allDao = db.allDao();

        // Create some school objects
        School[] s_array = {new School("School1"),
                new School("School2"),
                new School("School3")
        };
        // Insert the Schools into the database
        for (School s: s_array) {
            allDao.insertSchool(s);
        }

        // Create some Class objects
        Class[] c_array = {
                new Class("Class1"),
                new Class("Class2"),
                new Class("Class3")
        };
        // Insert the classes
        for (Class c: c_array) {
            allDao.insertClass(c);
        }

        // Create some Student Objects
        Student[] st_array = {
                new Student("Fred",3,3), new Student("Mary",1,2)
        };
        //Insert the Students
        for(Student st: st_array) {
            allDao.insertStudent(st);
        }

        // Get the Students with the School and Class information using POJO 1 (realtionship via joins)
        List<StudentAndSchoolAndClass> sasac = allDao.getStudentAndSchoolAndClass();
        // Log the data
        for(StudentAndSchoolAndClass ssc: sasac) {
            Log.d("STUDENTINFO1","Student Name = " + ssc.student.StudentName +
                    "
	 ID=" + ssc.student.StudentId + " SchoolID=" + ssc.student.SchoolId + " ClassID=" + ssc.student.ClassId +
                    "
		 School Name = " + ssc.school_name +
                    "
		 Class Name = " + ssc.class_name
                    );
        }
        // Get the Students with the School and Class information using POJO 2 (with @Relation's)
        List<StudentWithSchoolWithClass> swswc = allDao.getStudentWithSchoolWithClass();
        for(StudentWithSchoolWithClass ssc: swswc) {
            Log.d("STUDENTINFO2","Student Name = " + ssc.student.StudentName +
                    "
	 ID=" + ssc.student.StudentId + " SchoolID=" + ssc.student.SchoolId + " ClassID=" + ssc.student.ClassId +
                    "
		 School Name = " + ssc.schoolList.get(0).SchoolName +
                    "
		 Class Name = " + ssc.classList.get(0).ClassName
            );
        }
    }
}
  • 注意第一个选项中的学校和班级名称是班级的成员,而第二个选项中的学校和班级在列表中。由于学生将只有一个学校/班级,因此不需要遍历列表,因为第一个元素/项目(0)将是列表中唯一的元素/项目。

结果

当(第一次)运行上述程序时,数据库为:-

日志包含:-

2021-04-01 22:09:51.977 D/STUDENTINFO1: Student Name = Fred
         ID=1 SchoolID=3 ClassID=3
             School Name = School3
             Class Name = Class3
2021-04-01 22:09:51.977 D/STUDENTINFO1: Student Name = Mary
         ID=2 SchoolID=1 ClassID=2
             School Name = School1
             Class Name = Class2


2021-04-01 22:09:51.982 D/STUDENTINFO2: Student Name = Fred
         ID=1 SchoolID=3 ClassID=3
             School Name = School3
             Class Name = Class3
2021-04-01 22:09:51.982 D/STUDENTINFO2: Student Name = Mary
         ID=2 SchoolID=1 ClassID=2
             School Name = School1
             Class Name = Class2

这篇关于Android房间一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Android房间一对多关系

基础教程推荐