There is an updated edition of this book available! View Latest Edition
Home Android & Kotlin Books Saving Data on Android

Mastering Relations Written by Aldo Olivares

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

You can unlock the rest of this book, and our entire catalogue of books and videos, with a Professional subscription.

In the previous chapter, you learned all you need to know about tables, entities and annotations. You also learned how to create your database and how to get a runtime instance of it by using the Room.databaseBuilder method.

In this chapter, you are going to learn even more about entities by creating relations between them using foreign keys and the @Relation annotation. Along the way, you will learn:

  • How to create a relationship using primary keys and foreign keys.
  • How to define a one to many relationship in Room.
  • How to represent different kinds of relationships using entity-relationship diagrams.
  • How to use the @Embedded annotation.
  • How to use the @ForeignKey annotation.
  • How to use the @Relationship annotation.

Ready? Let’s get started.

Note: This chapter assumes you have basic knowledge of Kotlin and Android. If you’re new to Android, check out our Android tutorials. If you know Android, but are unfamiliar with Kotlin, take a look at Kotlin For Android: An Introduction.

Getting started

If you are following along with your own app, open it up. If not, don’t worry you can use the starter project for this chapter, which you can find in the attachments. Now, open the app in Android Studio 3.2 or greater by going to File ▸ New ▸ Import Project, and selecting the build.gradle file in the root of the project.

Once the starter project finishes loading and building, run the app on a device or emulator.

The DroidQuiz application
The DroidQuiz application

Great! The app is working as expected.

The code is basically the same as the previous chapter. But, if you are just getting started, here is a quick recap of the packages and the code:

  • The data package contains the db package and the model package. The db package contains the class that creates your Room database, while the model package contains all of the code for the entities created in the previous chapter.
  • The view package contains the code for all of the activities of your app.

You are no doubt eager to start writing some code. But, before that, you will need to learn a bit of theory first!

Relations and entity-relationship diagrams

In this chapter, we are going to create a relation between the Question entity and the Answer entity that you created in the previous chapter. The only problem is… you know… relationships are always hard to understand even if it is just between two single tables. Therefore, in this section, we are going to talk about a little tool that will help you to better understand the different kinds of relations between tables: entity-relationship diagrams.


Represents a component, object or a concept of a system. Concepts described by an entity can be concrete, such as a student or a car, or abstract, such as an event or a schedule. Entities are translated as tables when creating your database schema. They are commonly illustrated as rectangles in most ER diagrams:

The Student entity
Sce Gmefevc ihjaxp

The User entity
Zsi Odif ogwojt


A relationship tells you how two entities interact with each other and it’s usually represented as a verb surrounded by a diamond. For example, think about a student entity and a class entity. Their relationship could be described as follows:

Relation between entities
Faqinooc helceir upguyeax


Last but not least, the cardinality tells you the kind of relationship two entities have. There are three main cardinal relationships:

One to One relation
Ese lu Acu pogituax

One to Many relation
Aza li Mozx xewaqaox

Many to Many relation
Yiqt ti Popn vanadour

ER Cardinalities
OD Furwoxicofaos

Creating your relations

As briefly mentioned in the previous chapter, you will only need to create one relationship between the entities in your app, and its ER diagram looks like this:

One to Many relation between Question and Answers
Oda to Parn jepajuip wuntiud Qoolkiir egn Edpkanx

@Entity(tableName = "answer",
    foreignKeys = [//1
        ForeignKey(entity = Question::class,//2
            parentColumns = ["question_id"],//3
            childColumns = ["question_id"],//4
            onDelete = CASCADE)//5
@Entity(tableName = "answer",
    foreignKeys = [
        ForeignKey(entity = Question::class,
            parentColumns = ["question_id"],
            childColumns = ["question_id"],
            onDelete = CASCADE)
    indices = [Index("question_id")])//only this line changes
@Entity(tableName = "question", indices = [Index("question_id")])
@Query("SELECT * FROM question ORDER BY question_id")
fun getAllQuestions(): LiveData<List<Question>>

@Query("SELECT * FROM answer WHERE question_id = :questionId")
fun getAnswersForQuestion(questionId: Int): List<Answer>
class QuestionAndAllAnswers {
    var question: Question? = null

    @Relation(parentColumn = "question_id",//2
              entityColumn = "question_id")
    var answers: List<Answer> = ArrayList()//3
The final DroidQuiz application
Spi dahaj GqeegFeay idrlaxijouv

Key points

  • An entity relation diagram, ER diagram or ERD is a kind of flowchart that illustrates the relation between the components of a system.
  • Entities represent a component, object or a concept of a system. They are usually translated as tables in your database.
  • Entities in Crow’s Foot notation also include a list of attributes or properties that define them.
  • An attribute that can uniquely identify a record of your entity is known as a key attribute and they usually become primary keys in your database.
  • A relationship tells you how two entities interact with each other and it is usually represented as a verb.
  • The cardinality of an ERD tells you the kind of relationship that two entities have.
  • One to one relationship: When one entity can only be related to one and only one instance of the other entity.
  • One to many relationship: When one entity can be related to many instances of another entity.
  • Many to many relationship: When many instances of an entity can also be related to many instance of another entity.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

© 2022 Razeware LLC

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.