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?

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:

@Entity
public class Thingy {
  @Id private Long id;

  private long otherThingyId;

  @ToOne(joinProperty="otherThingyId")
  private OtherThingy otherThingy;

  // other good stuff here
}

@Entity
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 apparently resembled a Pokémon.

The Room Approach

The preview of this section is in an invisible, microscopic font.

Plans for Trips

The preview of this section was accidentally identified as an Android 'tasty treat' by the Cookie Monster.

Self-Referential Relations for Tree Structures

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

Using @Relation

The preview of this section is en route to Mars.

@Relation and @Query

The preview of this section is unavailable right now, but if you leave your name and number at the sound of the tone, it might get back to you (BEEEEEEEEEEEEP!).

Representing No Relation

The preview of this section is unavailable right now, but if you leave your name and number at the sound of the tone, it might get back to you (BEEEEEEEEEEEEP!).