簡介
Room 持久性庫在 SQLite 上提供了一個抽象層,以便在充分利用 SQLite 的強大功能的同時,能夠流暢地訪問數(shù)據(jù)庫。具體來說,Room 具有以下優(yōu)勢:
- 針對 SQL 查詢的編譯時驗證。
- 可最大限度減少重復和容易出錯的樣板代碼的方便注解。
- 簡化了數(shù)據(jù)庫遷移路徑。
dependencies {
val roomVersion = "2.4.2"
implementation("androidx.room:room-runtime:$roomVersion")
//在java中使用這個編譯注解
annotationProcessor("androidx.room:room-compiler:$roomVersion")
//在kotlin 項目中使用這個編譯注解
// To use Kotlin annotation processing tool (kapt)
kapt("androidx.room:room-compiler:$roomVersion")
// To use Kotlin Symbolic Processing (KSP)
ksp("androidx.room:room-compiler:$roomVersion")
// optional - Kotlin Extensions and Coroutines support for Room
implementation("androidx.room:room-ktx:$roomVersion")
// optional - RxJava2 support for Room
implementation("androidx.room:room-rxjava2:$roomVersion")
// optional - RxJava3 support for Room
implementation("androidx.room:room-rxjava3:$roomVersion")
// optional - Guava support for Room, including Optional and ListenableFuture
implementation("androidx.room:room-guava:$roomVersion")
// optional - Test helpers
testImplementation("androidx.room:room-testing:$roomVersion")
// optional - Paging 3 Integration
implementation("androidx.room:room-paging:2.5.0-alpha01")
}
Room 包含三個主要組件:
- 數(shù)據(jù)庫類,用于保存數(shù)據(jù)庫并作為應用持久性數(shù)據(jù)底層連接的主要訪問點。
- 數(shù)據(jù)實體 ,(Entity)用于表示應用的數(shù)據(jù)庫中的表, 一個Entity 對應數(shù)據(jù)庫中的一個表,Entity類時sqlite 表結構對Java類的映射,在Java中,可以被看做一個Model
- 數(shù)據(jù)訪問對象 (DAO),提供您的應用可用于查詢、更新、插入和刪除數(shù)據(jù)庫中的數(shù)據(jù)的方法。

room_architecture.png
總的來說,一個Entity就是一張表,而沒張表都需要一個Dao對象,用于對表進行增刪改查。Room 數(shù)據(jù)庫在被實例化之后,我們就可以通過數(shù)據(jù)庫實例得到Dao 對象,然后同Dao對象對數(shù)據(jù)庫進行操作。
Room 的具體使用
創(chuàng)建一個表
//設置表名字
@Entity(tableName = "person_table")
data class Person (
//設置主鍵,并且該字段由 SQLite 自動生成
@PrimaryKey(autoGenerate = true)
/**設置字段名稱,類型為INTEGER 類型:
* UNDEFINED :未定義的類型。 將根據(jù)類型進行解析。
* TEXT : 字符串類型
* INTEGER: 整數(shù)或者bool類型
* REAL: float 或者 double 類型
* BLOB: 二進制數(shù)據(jù)類型
*/
@ColumnInfo(name = "id", typeAffinity = ColumnInfo.INTEGER)
val id :Int,
@ColumnInfo(name = "name", typeAffinity = ColumnInfo.TEXT)
val name:String,
@ColumnInfo(name="age", typeAffinity = ColumnInfo.INTEGER)
val age:Int,
/**
* 該類型不會被持久化
* 由于Room 只能識別一個構造器,如果希望多個構造器,可以使用@Ignore 修飾這個構造器,讓Roow忽略這個構造器,
*/
@Ignore
val sex:String
)
創(chuàng)建表的處理方法
//定義表的操作
@Dao
interface PersonDao {
//插入一條數(shù)據(jù)
@Insert
fun insert(p: Person)
//刪除一條數(shù)據(jù)
@Delete
fun delete(p: Person)
//更新一條數(shù)據(jù)
@Update
fun update(p: Person)
//查詢全部數(shù)據(jù)
@Query("SELECT * FROM person_table")
fun queryAll(): List<Person>
}
創(chuàng)建數(shù)據(jù)庫
@Database(entities = [Person::class], version = 1)
abstract class PersonDatabase : RoomDatabase() {
abstract fun personDao(): PersonDao
companion object {
private var instance: PersonDatabase? = null
fun get(context: Context?): PersonDatabase? {
if (instance == null) {
context?.applicationContext?.let {
instance = Room.databaseBuilder(it, PersonDatabase::class.java, "Sample.db")
.allowMainThreadQueries().build()
}
}
return instance
}
}
}