Room 是Jetpack中的ORM組件,Room 可以簡化SQLite數據庫操作。
Room 在 SQLite 上提供了一個抽象層,以便在充分利用 SQLite 的強大功能的同時,能夠流暢地訪問數據庫。
-
添加依賴
// 使用kotlin開發必須使用插件kapt添加room-compiler
plugins {
id 'kotlin-kapt'
}
dependencies {
val roomVersion = "2.4.0"
// Java開發
// 基礎功能
implementation("androidx.room:room-runtime:$roomVersion")
annotationProcessor("androidx.room:room-compiler:$roomVersion")
// Kotlin開發(添加上邊的kotlin-kapt插件)
// 支持協程(包含基礎功能)
implementation("androidx.room:room-ktx:$roomVersion")
// 必須引用
kapt("androidx.room:room-compiler:$roomVersion")
}
Room包含三個組件,Entity、Dao、Database
-
新建Entity
// 該注解代表數據庫一張表,tableName為該表名字,不設置則默認類名
// 注解必須有!!tableName可以不設置
@Entity(tableName = "User")
data class User(
// 該標簽指定該字段作為表的主鍵, 自增長。注解必須有??!
@PrimaryKey val id: Int? = null,
// 該注解設置當前屬性在數據庫表中的列名和類型,注解可以不設置,不設置默認列名和屬性名相同
@ColumnInfo(name = "content", typeAffinity = ColumnInfo.TEXT)
val content: String?
// 該標簽用來告訴系統忽略該字段或者方法,顧名思義:不生成列
@Ignore
)
-
創建Dao,Dao一定是個接口或抽象類。一個Entity代表著一張表,而每張表都需要一個Dao對象,方便對這張表進行增刪改查
@Dao
interface UserDao {
@Query("SELECT * FROM User")
fun getAll(): List<User>
@Query("SELECT * FROM User WHERE content LIKE :content LIMIT 1")
fun findByContent(content: String): User
@Insert
fun insertAll(vararg users: User)
@Delete
fun delete(user: User)
}
-
創建Database,抽象類,繼承RoomDatabase
@Database(
// 指定該數據庫有哪些表,若需建立多張表,以逗號相隔開
entities = [User::class],
// 指定數據庫版本號,后續數據庫的升級正是依據版本號來判斷的
version = 1
)
abstract class AppDatabase : RoomDatabase() {
// 提供所有Dao,對一一對應的數據庫表進行操作
abstract fun getUserDao(): UserDao
companion object {
private const val DB_NAME = "app_name.db"
@Volatile
private var INSTANCE: AppDatabase? = null
fun getDatabase(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this){
val instance = Room.databaseBuilder(
context.applicationContext, AppDatabase::class.java,
DB_NAME
).build()
INSTANCE = instance
instance
}
}
}
}
-
代碼中調用
class DataRepository{
companion object {
@Volatile
private var instance: DataRepository? = null
@Synchronized
fun getInstance(): DataRepository {
if (instance == null) {
instance = DataRepository()
}
return instance!!
}
}
/**
* 查詢用戶信息
*/
fun getUser(context: Context): User? {
val userList = AppDatabase.getDatabase(context).getUserDao().getAll()
if (userList.isNullOrEmpty()) {
return null
}
val content = userList[0].content
return Gson().fromJson(content, UserInfoBean::class.java)
}
/**
* 儲存用戶信息
*
* @param content 用戶信息Bean Json
*/
fun saveUser(context: Context, content: String?) {
val dao = AppDatabase.getDatabase(context).getUserDao()
val queryInfo = dao.findFirst()
if (queryInfo == null) {
val user = User(content = content)
dao.insert(user)
} else {
queryInfo.content = content
dao.update(user)
}
}
}
-
使用注意點
1. cannot find implementation for com.aheading.request.database.AppDatabase. AppDatabase_Impl does not exist
譯:無法找到com.aheading.request.database.AppDatabase的實現。AppDatabase_Impl不存在。即數據庫創建失敗
解決方案:
1.1 檢查所有注解是否添加
@Entity
@PrimaryKey
@Dao
@Database(
entities = [User::class],
version = 1
)
1.2 檢查頂部依賴是否配置正確。若多模塊開發,Base模塊中已配置相關依賴,其他模塊只要用到了Database,也需要在build.gradle中添加如下依賴包,不需要功能依賴:
plugins {
id 'kotlin-kapt'
}
dependencies {
kapt("androidx.room:room-compiler:$roomVersion")
}
2. Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
譯:無法在主線程上訪問數據庫,因為它可能會鎖定UI很長一段時間。
解決方案:
方案一:創建數據庫時設置允許主線程訪問 allowMainThreadQueries(),不推薦!
Room.databaseBuilder(
AppHelper.mContext, AppDatabase::class.java,
DB_NAME
)
// 禁用Room的主線程查詢檢查(慎用!!!)
.allowMainThreadQueries()
.build()
方案二:子線程中調用,我是使用了協程進行操作。
viewModelScope.launch(Dispatchers.IO) {
val localUser = DataRepository.getInstance().getUser(context)
user.postValue(localUser)
withContext(Dispatchers.Main) {
// 切換到主線程執行UI相關操作
...
}
}
3. Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.
譯:Room無法驗證數據完整性??雌饋砟呀浉牧思軜?,但忘記更新版本號。你可以通過增加版本號來解決這個問題。就是你修改了數據庫,但是沒有升級數據庫的版本。
解決方案:
第一步:更新數據庫的注解配置(entitys和版本號),我這里新增表 PersonTable
@Database(
entities = [User::class,PersonTable::class],
version = 2
)
第二步:添加Migration
數據庫升級用到的sql語句,不用自己寫,去自動生成的類中copy。否則,自己寫和自動生成的語句不一致的話,會報錯。默認生成的語句在你的 XxxDatabase_Impl 這個類中,例:AppDatabase_Impl
// AppDatabase_Impl中代碼
public void createAllTables(SupportSQLiteDatabase _db) {
_db.execSQL("CREATE TABLE IF NOT EXISTS `student` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `age` TEXT NOT NULL, `roomId` INTEGER NOT NULL)");
_db.execSQL("CREATE TABLE IF NOT EXISTS `class_room` (`class_id` INTEGER NOT NULL, `class_name` TEXT NOT NULL, PRIMARY KEY(`class_id`))");
_db.execSQL("CREATE TABLE IF NOT EXISTS `address` (`addressId` INTEGER NOT NULL, `addressName` TEXT NOT NULL, PRIMARY KEY(`addressId`))");
_db.execSQL("CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)");
_db.execSQL("INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '7cbdd6263025181ec070edd36e1118eb')");
}
// 1. 新增數據庫版本升級Migration
val MIGRATION_1_2: Migration = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL(
// 添加IF NOT EXISTS和IF EXISTS沒壞處
"CREATE TABLE IF NOT EXISTS 'PersonTable'('id' INTEGER, 'content' TEXT, PRIMARY KEY('id'))"
)
}
}
// 2. 數據庫新建處addMigrations
Room.databaseBuilder(
AppHelper.mContext, AppDatabase::class.java,
DB_NAME
)
.addMigrations(MIGRATION_1_2)
.build()