Relations in Room

SQLite is a relational database. So far, we have not talked about that, focusing instead on standalone entities.

Room supports entities being related to other content in other tables. Room does not support entities being directly related to other entities, though.

And if that sounds strange, there is “a method to the madness”.

(or, in Kotlin, “a function to the foolishness”)

In this chapter, we will explore how you implement relational structures with Room and why Room has the restrictions that it does.

The Classic ORM Approach

Java ORMs have long supported entities having relations to other entities, though not every ORM uses the “entity” term.

One Android ORM that does is greenDAO. It allows you to use annotations to indicate relations, such as in this Java snippet:

public class Thingy {
  @Id private Long id;

  private long otherThingyId;

  private OtherThingy otherThingy;

  // other good stuff here

public class OtherThingy {
  @ID private Long id;

These annotations result in getOtherThingy() and setOtherThingy() methods to be synthetically added to Thingy (or, more accurately, to a hidden subclass of Thingy, but for the purposes of this section, we will ignore that). Which OtherThingy our Thingy relates to is tied to that otherThingyId field, which is stored as a column in the table. When you call getOtherThingy(), greenDAO will query the database to load in the OtherThingy instance, assuming that it has not been cached already.

That is where the threading problem creeps in.

Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.