<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Norman Vicente</title>
    <description>The latest articles on DEV Community by Norman Vicente (@normanaspx).</description>
    <link>https://dev.to/normanaspx</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F444049%2F7b88f763-df41-4404-94b5-9c56ee02f378.jpg</url>
      <title>DEV Community: Norman Vicente</title>
      <link>https://dev.to/normanaspx</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/normanaspx"/>
    <language>en</language>
    <item>
      <title>Android Room: How works One to many relationship + example
</title>
      <dc:creator>Norman Vicente</dc:creator>
      <pubDate>Thu, 30 Jul 2020 23:23:18 +0000</pubDate>
      <link>https://dev.to/normanaspx/android-room-how-works-one-to-many-relationship-example-5ad0</link>
      <guid>https://dev.to/normanaspx/android-room-how-works-one-to-many-relationship-example-5ad0</guid>
      <description>&lt;p&gt;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.&lt;/p&gt;

&lt;h1&gt;
  
  
  How works room?
&lt;/h1&gt;

&lt;p&gt;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.&lt;br&gt;
To know the basic notions of room you can follow this tutorial &lt;a href="https://developer.android.com/training/data-storage/room" rel="noopener noreferrer"&gt;https://developer.android.com/training/data-storage/room&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Android one to many in room explanation:
&lt;/h2&gt;

&lt;p&gt;For this example using basic concepts of databases and room, first declare their entities Course.java and Student.java:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity(tableName = "course")
public class Course {

    @PrimaryKey(autoGenerate = true)
    private long id_course;
    private String courseName;

    public long getId_course() {
        return id_course;
    }

    public void setId_course(long id_course) {
        this.id_course = id_course;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public Course(String courseName) {
        this.courseName = courseName;
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Course.java is our parent class and we add an id that is auto generated with the @PrimaryKey annotation (autoGenerate = true)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity(tableName = "student")
public class Student {

    @PrimaryKey(autoGenerate = true)
    private long id_student;

    @ForeignKey
            (entity = Course.class,
                    parentColumns = "id_course",
                    childColumns = "id_fkcourse",
                    onDelete = CASCADE
            )
    private long id_fkcourse;

    private String studentName;

    public long getId_student() {
        return id_student;
    }

    public Student(String studentName) {
        this.studentName = studentName;
    }

    public void setId_student(long id_student) {
        this.id_student = id_student;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public long getId_fkcourse() {
        return id_fkcourse;
    }

    public void setId_fkcourse(long id_course) {
        this.id_fkcourse = id_course;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/*** EXCLUSIVE CLASS TO MANAGE ONE TO MANY IN ROOM  ***/
public class CourseWithStudents {

    @Embedded
    public Course course;
    @Relation(
            parentColumn = "id_course",
            entityColumn = "id_student"
    )
    public List&amp;lt;Student&amp;gt; students;

    public CourseWithStudents(Course course, List&amp;lt;Student&amp;gt; students) {
        this.course = course;
        this.students = students;
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;/p&gt;

&lt;h2&gt;
  
  
  Add Dao interface:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Dao
public interface CourseDao {

    @Transaction
    @Insert
    long insertCourse(Course course);

    @Insert
    void insertStudents(List&amp;lt;Student&amp;gt; students);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;br&gt;
Continuing with the MVVM pattern we already have to have our classes for ViewModel and Repository:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CourseRepository {

    private CourseDao courseDao;

    public CourseRepository(Application application) {
        Database database = Database.getDatabase(application);
        courseDao = database.courseDao();
    }

    public void insert(CourseWithStudents courseWithStudents) {
        new insertAsync(courseDao).execute(courseWithStudents);
    }

    private static class insertAsync extends AsyncTask&amp;lt;CourseWithStudents, Void, Void&amp;gt; {
        private CourseDao courseDaoAsync;

        insertAsync(CourseDao courseDao) {
            courseDaoAsync = courseDao;
        }

        @Override
        protected Void doInBackground(CourseWithStudents... courseWithStudents) {

            long identifier = courseDaoAsync.insertCourse(courseWithStudents[0].course);

            for (Student student : courseWithStudents[0].students) {
                student.setId_fkcourse(identifier);
            }
            courseDaoAsync.insertStudents(courseWithStudents[0].students);
            return null;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In order for the inserting process not to conflict with the main thread we must add an asynchronous class that handles it.&lt;/p&gt;

&lt;p&gt;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.&lt;br&gt;
This snippet is very important what understand because manage the relationship.&lt;br&gt;
Viewmodel class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CourseViewModel extends AndroidViewModel {

    public CourseViewModel(@NonNull Application application) {
        super(application);
        courseRepository = new CourseRepository(application);
    }

    private CourseRepository courseRepository;

    public void insertCourseWithStudents(CourseWithStudents courseWithStudents){
        courseRepository.insert(courseWithStudents);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fmax%2F606%2F1%2A8e-sB-o7P__blCGX7OEvzg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fmax%2F606%2F1%2A8e-sB-o7P__blCGX7OEvzg.png" title="Logo Title Text 1" alt="alt text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Sqlite looks like:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fmax%2F409%2F1%2ALflUE29SOROx70YIKFe2-w.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fmax%2F409%2F1%2ALflUE29SOROx70YIKFe2-w.jpeg" title="Logo Title Text 1" alt="alt text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fmax%2F351%2F1%2AzEBw9AyNz29ZqQJfMSN75w.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fmax%2F351%2F1%2AzEBw9AyNz29ZqQJfMSN75w.jpeg" title="Logo Title Text 1" alt="alt text"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>android</category>
      <category>java</category>
    </item>
  </channel>
</rss>
