Android Room: How works One to many relationship + example
Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. One-to-many relationship exists when one row in table A may be linked with many rows in table B, but one row in table B is linked to only one row in table A.
How works room?
The importance of using room to work classes as entities is very powerful but its documentation is very poor on how to work the relations between entities.
To know the basic notions of room you can follow this tutorial https://developer.android.com/training/data-storage/room
Android one to many in room explanation:
For this example using basic concepts of databases and room, first declare their entities Course.java and Student.java:
Course.java is our parent class and we add an id that is auto generated with the @PrimaryKey annotation (autoGenerate = true)
In the child class Student.java an attribute must be added that contains the id of the parent class, in this case id_fkcourse and the annotation @ForeigKey will be used to make the relationship between entities.
To do this, create a new data class where each instance holds an instance of the parent entity and a list of all corresponding child entity instances. Add the @Relation
annotation to the instance of the child entity, with parentColumn
set to the name of the primary key column of the parent entity and entityColumn
set to the name of the column of the child entity that references the parent entity's primary key.
Add Dao interface:
It’s important to mention that the @Transaccion annotation should be used. One method will be for the course and another for the list of assigned students.
Continuing with the MVVM pattern we already have to have our classes for ViewModel and Repository:
In order for the inserting process not to conflict with the main thread we must add an asynchronous class that handles it.
long identifier = courseDaoAsync.insertCourse(courseWithStudents[0].course);
for (Student student : courseWithStudents[0].students) {
student.setId_fkcourse(identifier);
}
courseDaoAsync.insertStudents(courseWithStudents[0].students);
In the for instruction we assign each student the id of the course that was inserted. This id is generated automatically and we only have to obtain it by assigning a long data type to the result.
This snippet is very important what understand because manage the relationship.
Viewmodel class:
Finally these are the classes that are in charge of managing the relationship of one to many. The CourseWithStudents class is very important since it handles the relationship at the entity level linking both course models with their students.
The missing classes like activities and database are github repository take a look and give it a star :)