The following is the first few sections of a chapter from Android's Architecture Components, plus headings for the remaining major sections, to give you an idea about the content of the chapter.

Room and Relations

SQLite is a relational database. At some point, Room should support relations. Right?


Well, actually, the story is a bit more complicated than that. Yes, 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”.

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:

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.

A History of Threading Mistakes

The preview of this section is en route to Mars.

The Room Approach

The preview of this section left for Hollywood to appear in a reality TV show.

Plans for Trips

The preview of this section is being chased by zombies.

Self-Referential Relations for Tree Structures

The preview of this section was lost in the sofa cushions.

Using @Relation

The preview of this section was lost due to a rupture in the space-time continuum.

@Relation and @Query

The preview of this section was traded for a bag of magic beans.

Representing No Relation

The preview of this section is off trying to sweet-talk the Khaleesi into providing us with a dragon.