Database by Room in Kotlin
Storing data into a database using SQLite API can be a hectic job for developers, writing lots of code and handling to perform any database operations. Android’s official site highly recommends Room instead of SQLite. However, if you prefer to use SQLite APIs directly. Let’s get started to learn Room in Kotlin for better application development.
The room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.
There are 3 major components in Room:
- Database: Contains the database holder and serves as the main access point. This is an abstract class that extends
RoomDatabase
it has methods without argument and annotated by @Dao. - Entity: This is a class annotated by @Entity that represents a table and its methods are table fields.
- DAO: Contains the methods used for accessing the database. This is an interface that has methods like Insert, update, delete and query. The class is annotated by @Dao and the methods are annotated by operations like for insert @Insert Update @Update Delete @Delete and for query @Query.
Let’s begin with the coding for better understanding :)
For enabling room in your newly created project you have to add the dependency library in your project app Gradle.
// Room dependencies
implementation 'androidx.room:room-runtime:2.0.0'
kapt 'androidx.room:room-compiler:2.0.0'
First, we need to create an Entity class for table creation, so here we are creating a class named Employee.kt like this.
@Entity(tableName = "Employee")
data class Employee( @PrimaryKey(autoGenerate = true)
var id: Long = 0, @ColumnInfo(name = "employeeName")
var employeeName: String, @ColumnInfo(name = "employeeID")
var employeeID: String, @ColumnInfo(name = "employeeJob")
var employeeJob: String
)
This is a data class which is having constructor parameters like id, employeeName, emplyeeId, employeeJob the annotation @ColumnInfo is used for giving the name of the field in DB. @PrimaryKey(autoGenerate = true) for making the field as the primary key.
Now create Dao this is an Interface named EmployeeDao this will contains all the database operation methods.
@Dao
interface EmployeeDao {
@Insert
fun insert(employee: Employee)
@Delete
fun delete(employee: Employee)
@Query("SELECT * FROM Employee")
fun getAll(): List<Employee>
@Update
fun update(employee: Employee)
@Query("SELECT count(*) FROM Employee")
fun count(): Int
As we have understood the required annotations for the database operations which are present in the Dao interface.
The last class we are going to create is the DatabaseService.kt class which is an abstract class extends with RoomDatabase.
@Database(
entities = [
Employee::class
],
version = 1,
exportSchema = false
)
abstract class DatabaseService : RoomDatabase() {
abstract fun employeeDao(): EmployeeDao
}
We can see this class has an abstract method as employeeDao() which is returning EmplyeeDao and also we have to tell the to room library that this is the Database class by annotation @Database ( ) the database annotation required 2 parameters first is entities i.e an array having entity names, and second is version that is a database version. The exportSchema is optional, I am putting it as false.
Finally, its time to access all database table methods for database operations. you can make a method in your project Application class for best practice, and this is a database instance that should not be created multiple times so make it as a singleton.
/**
* Create database instance
*/
fun getDatabase(): DatabaseService {
if(databaseService == null){
databaseService = Room.databaseBuilder(
this@EmployeeApplication,
DatabaseService::class.java,
"employee_database"
).build()
}
return databaseService
}
Roo.databaseBuilder() required context, database class where the RoomDatabase extends and the database name, this is a builder class so we have to build it.
Now you can get the DatabseService instance and its all Daos of your tables by calling getDatabase() method, you can also use Dagger library for getting the DatabaseService instance for better application structure.
Try to insert the Employee object and print the DB data into logs for understanding how the Room works. Soon I will upload a sample code link of GitHub till then.
Happy coding and Thank you! :)