One-to-many relation in Room

Asim picture Asim · Jan 25, 2018 · Viewed 14.6k times · Source

I've been using SugarDB for most of my projects in the past. It was easy to use and satisfied most of my requirements but since that project has been abandoned, decided to look at alternatives and Room seems like the best option.

However, some basic things are quite confusing in Room. My Object uses Gson to populate data from a webservice, and as such as links to other objects. As an example, consider the classes below:

@Entity
public class TestModel
{
    @PrimaryKey(autoGenerate = true)
    private int id;
    private String name;
    private String age;
    private List<Book> issuedBooks;
}

public class Book
{
    private String title;
    private int ISBN;
}

Now if my first class is annotated as the Entity, will this automatically treat classes referenced inside it as entities as well?

If I save an object of TestModel, will it save the list of Books with it to the database?

Answer

Cheok Yan Cheng picture Cheok Yan Cheng · Apr 1, 2018

I guess you can do it this way.

@Entity
public class TestModel {
    @PrimaryKey
    public int id;          // TestModel id
    public String name;
    public String age;
}

@Entity
public class Book {
    @PrimaryKey
    public int id;          // Book id
    public int testModelId; // TestModel id
    public String title;
    public int ISBN;
}

public class TestModelWithBooks {
   @Embedded
   public TestModel testModel;

   @Relation(parentColumn = "id", entityColumn = "testModelId", entity = Book.class)
   public List<Book> books;
}

For their Dao, you can write it this way.

@Dao
public interface TestModelDao {
    @Query("SELECT * FROM TestModel")
    public List<TestModelWithBooks> loadTestModelsWithBooks();
}