ROOM Database
- Room is an ORM (Object Relational Mapper) for SQLite database in Android developement and part of Android Jetpack.
- Provides an abstraction layer over SQLite database
- Amount of boilerplate code is reduced
- Compile-time verification of SQL queries
ROOM Database components
- It has 3 main components Entity, Database, DAO.
- Entity is data class annotated with @Entity is like creating a table in SQLite and the variables in the model class are like columns in the table.
- Database is an abstract class which extends RoomDatabase and has list of entities associated with the database.
- DAO(Data Access Object) is an interface which defines the operations to be performed in our database.
ROOM Database Implementation
Step 1 creating Entity data class
@Entity(tableName = "yourOwnTableName")
data class LocalData(
val column1: String?,
val column2: String?,
@PrimaryKey(autoGenerate = true) val product_local_id: Int?= null
)
Step 2 creating Database
@Database(entities = [LocalData::class], version = 1, exportSchema = false)
@TypeConverters
abstract class LocalDB : RoomDatabase() {
abstract fun localDataDao() : LocalDataDAO
companion object{
private var instance : LocalDB ? = null
fun getInstance(context: Context) : LocalDB ?{
if(instance == null){
synchronized(LocalDB ::class){
instance = Room.databaseBuilder(context.applicationContext, LocalDB::class.java, "localBD.db").allowMainThreadQueries().build()
}
}
return instance
}
fun destroyInstance(){
instance = null
}
}
}
Step 3 creating DAO
@Dao
interface LocalDAO {
@Insert
fun insertData(productEntity: LocalData) : Long
@Delete
fun deleteData(productEntity: LocalData) : Int
@Query("Select * from yourOwnTableName")
fun showAllProducts(): List<LocalData>
@Query("SELECT COUNT(*) FROM yourOwnTableName")
fun totalProducts(): Long
}
Step 4 is optional is creating repository
class ProductRepository(context: Context) {
var dbms : LocalDAO = LocalDB.getInstance(context)?.localDataDao()!!
fun insertData(productEntity: LocalData) : Long{
return dbms.insertData(productEntity)
}
fun deleteData(productEntity: LocalData) : Int{
return dbms.deleteData(productEntity)
}
fun getAllData() : List<LocalData> {
return dbms.showAllProducts()
}
fun checkProductExist(id : Int) : Boolean{
return dbms.exists(id)
}
fun totalProductsInCart() : Long{
return dbms.totalProducts()
}
}