What is Room Persistence Library?
Room is a library built on top of SQLite that provides a more convenient and structured way to manage your Android app's local database,lets you work with your data as Kotlin objects (data classes) instead of writing raw SQL queries this simplifies database interactions and also checks your SQL queries at compile time. This helps us to catch errors early in the development cycle. so kets get started.
Dependencies
dependencies {
// Room
implementation("androidx.room:room-runtime:2.5.0")
implementation("androidx.room:room-ktx:2.5.0")
kapt("androidx.room:room-compiler:2.5.0")
}
Key Components
Entity
@Entity(tableName = "word_table")
data class Word(
@PrimaryKey val word: String
)
Entity is a Kotlin data class representing a single table in the database,each property of the class corresponds to a column in the table and each entity is annotates with @Entity and it has certain optional parameters
DAO (Data Access Object)
@Dao
interface WordDao {
@Query("SELECT * from word_table ORDER BY word ASC")
fun getAllWords(): LiveData<List<Word>>
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(word: Word)
}
A DAO is an Interface that helps us to define methods to interact with your database, the methods are annotated with SQL operations (@Query, @Upsert, @Insert, @Update, @Delete) and @Transacation and do note interface has to be annotated with @Dao.
Room Database
@Database(entities = [Word::class], version = 1, exportSchema = false)
abstract class WordRoomDatabase : RoomDatabase() {
//dao
abstract fun wordDao(): WordDao
}
An abstract class extending RoomDatabase that serves as the entry point to the database and is annotated with @Database annotation where you must you declare all the entiy's that the database is expected to use and wherer you can register the version and migration detail
Manually Creating a Database
val dataBase = Room.databaseBuilder(applicationContext,
YourDataBaseName::class.java,
"your_custom_database_name")
.build()
Interacting with the Database
//accessing dao from database
val wordDao = dataBase.wordDao()
//operation with the dao
wordDao.insert(Word("hello"))
wordDao.getAllWords()
Comments
Post a Comment