-
Notifications
You must be signed in to change notification settings - Fork 0
Room β Layers of room database
Devrath edited this page Oct 14, 2023
·
12 revisions
Contents |
---|
Block diagram |
Classes Involved |
Layred blocks explained using code |
How the classes involved interact with each other |
- 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 thedata class
objects in the database.
- 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.
- We use the annotation
@DAO
will mark the class asdata 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.
Contents |
---|
Entity class |
Database class |
DAO 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.
- 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 themain
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 is aninterface
class that has a set ofabstract
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 theDAO
s` we defined.
- The
user(Android application)
requests data. - Data requested from the App to
DAO
layer. - The
DAO
layer takes responsibility toget
/send
the datafrom
/to
thedatabase
. - The
DAO
usesentities
for this purpose to achieve this.