Room - robielcpnv/What_the_dog GitHub Wiki

ROOM

Room is the official ORM for setting up data persistence in an Android application. This library shines by its efficiency, its simplicity and its caching system.

Room provides the following benefits:

  • Compile-time verification of SQL queries.
  • less boilerplate code.
  • Streamlined database migration paths /Easily integrated with other Architecture

image

Figure 1. Diagram of Room library architecture.

The three main components of Room are listed below:

  1. The Entity objects that represent the records of the application's database tables. In general, there is one Entity class per table.
  2. The Database object that represents the application's database.
  3. DAO objects that contain the functions that allow the tables to be manipulated. In general, there is one DAO class per table.

Entity

Represents a table within the database. Room creates a table for each class that has @Entity annotation, the fields in the class correspond to columns in the table. Therefore, the entity classes tend to be small model classes that don’t contain any logic.

Entities annotations

@Entity — every model class with this annotation will have a mapping table in DB

  • foreignKeys — names of foreign keys
  • indices — list of indicates on the table
  • primaryKeys — names of entity primary keys
  • tableName @PrimaryKey — as its name indicates, this annotation points the primary key of the entity. autoGenerate — if set to true, then SQLite will be generating a unique id for the column

@PrimaryKey(autoGenerate = true)

@ColumnInfo — allows specifying custom information about column

@ColumnInfo(name = “column_name”)

@Ignore — field will not be persisted by Room

@Embeded — nested fields can be referenced directly in the SQL queries.1. 1.

Dao

DAOs are responsible for defining the methods that access the database. We can simply define our queries using annotations in the Dao class.

Database

Contains the database holder and serves as the main access point for the underlying connection to your app’s persisted, relational data.

To create a database we need to define an abstract class that extends RoomDatabase. This class is annotated with @Database, lists the entities contained in the database, and the DAOs which access them.

The class that’s annotated with @Database should satisfy the following conditions:

  • Be an abstract class that extends RoomDatabase.
  • Include the list of entities associated with the database within the annotation.
  • Contain an abstract method that has 0 arguments and returns the class that is annotated with [@Dao]

Repository

A repository is not actually part of the Room library. It is just considered a best practice in coding when dealing with databases.

A repository manages queries and allows us to use multiple backends. A repository implements the logic for deciding whether to fetch data from a network of to use results cached in the local database.

Source