Hi all, the topic of this article is about Jetpack Room. Room makes it easy to work with SQLite objects. Queries in Rooms are checked at compile time. It has fewer code blocks than SQLite (like Select * from). It is easy to integrate with Jetpack elements.
Jetpack Room consists of 3 main layers
1-Entities (Model )
We can think of it as the model classes we keep. It just takes @Entities with Room annotations and specifies that it will use Room in this model class. If we think based on SQLite, there were tables here, actually, Entities, act as a mapping between these tables on the database.
@Entities: Creates a table for each class.
@ColumnInfo: Column customization name, leaving it blank will assign the variable name.
@Embeded: We express the columns that we will use in common in each table with these annotations.
Let’s see it as a code by adding our library via build.gradle :)
def roomVersion = "2.4.0"implementation "androidx.room:room-runtime:$roomVersion"
implementation "androidx.room:room-ktx:roomVersion"note : For kapt add in plugins -> id 'kotlin-kapt'
2-DAO (Data Access Object)
Here we define our methods of reaching the database layer and DAO is defined as an interface.
@Instert(insert data), @Delete(delete data) and We can also process annotations according to the item id. We will see below.
@Query: We perform operations with SQL (such as Select*from) codes with
@Dao: We specified Room integration with this annotation
When making @Insert, we can specify what to do if confusion occurs below(Replace) (line 12)
We specify that we will use Room with @Database annotations
Entities: Model or defined entities.
Version: We can do a version update so that there is no confusion during model changes.
Exportschema: If there is no schema control created, false can be entered, if we want to export the database to a schema (export the schema), true is entered.
Abstract: Class and function objects cannot be created, because they will be abstract.
I will perform the database builder process with D.I. Let’s start with the library plugins first.
def koinVersion = "3.1.2"implementation "io.insert-koin:koin-core:$koinVersion"
In line 4 ; we enter our DB class(x::class.java), DB name(x_database) with databaseBuilder.
In line 5: FallBackToDescructiveMigration : If the previous database does not have a version update or is incorrect, Room will recreate the database tables and move data and ensure that the DB is rebuilt instead of crashing.
Note: Don’t forget to define android:name=”.application.xxx” application in Manifest!!
In my next article, we will create Unit Test for Room :)