Skip to content

Room ‐ Layers of room database

Devrath edited this page Oct 14, 2023 · 12 revisions

Block diagram

Classes Involved

Database

  • We use the annotation @database to mark the class as a database class.
  • This class will be an abstract class.
  • This class extends RoomDatabase as its parent.
  • This will be the access point for the underline connection.
  • This class defines the list of entities and the data class objects in the database.

Entities

  • We use the annotation @entity to mark the class as an entity class.
  • For each entity, a row is created in the database to hold items.
  • It represents the table within the database.

DAO

  • We use the annotation @DAO will mark the class as data access object.
  • DAO is the main component of the room responsible for defining the methods that access the database.
  • They are involved in getting the changes from the database and persist changes to the database.

Layered blocks explained using code

Contents
Entity class
Database class
DAO class

Entity class

  • With the @Entity, we can provide the name for the table.
  • @PrimaryKey is the unique name provided for one column of a table. The primary key also helps in differentiating every object in the database.
  • With @ColumnInfo We can also provide a custom name for the column so that the table is created with that name.

Database class

  • Here we define the database version of the database
  • @Database annotation is used for our class ( w.k.r - our database class extends room database). The annotation accepts two params
    • Array of entity classes that we define.
    • Version code for the database is added in this parameter.
  • If we don't use coroutines then we need to explicitly mention the allowMainThreadQueries thread because room by default cannot run in the main thread.
  • We define a function that returns the instance of this class.
  • Then we add it in the application class and mention to access by lazy loading

DAO class

  • DAO class is an interface class that has a set of abstract methods.
  • Each abstract method signifies an operation for the database.
  • The interface is annotated with @Dao.
  • Abstract method to be a suspend method to be used in coroutines.
  • We can mention @Query and define a custom query on that abstract method.
  • We can mention @Insert, @Update, @Delete and define respective operations for the room database.
  • If we use @Insert, we have the option to mention a strategy to replace the row if an existing row is already added.
  • Add an abstract method in the database class we defined earlier that has the return type to the DAOs` we defined.

How the classes involved interact with each other

Untitled Diagram drawio

  • The user(Android application) requests data.
  • Data requested from the App to DAO layer.
  • The DAO layer takes responsibility to get/send the data from/to the database.
  • The DAO uses entities for this purpose to achieve this.