一.导入依赖:
implementation "androidx.activity:activity-ktx:1.1.0"
implementation "androidx.fragment:fragment-ktx:1.2.5"
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2'
二.创建RoomdataBasele类
/**
* entities 数据库里存入的表,可是多个
* version 数据库的版本号
* exportSchema 是否生成json文件,用于查看数据库的结构
*/
@Database(entities = [User::class],version = 1,exportSchema = false)
abstract class AppDataBase : RoomDatabase() {
abstract fun UserDao():UserDao //Dao 对象
companion object{
private var instance:AppDataBase?=null
fun getInstance(context:Context):AppDataBase{
//对象锁
return instance?: synchronized(this) {
//上下文 数据库名字
Room.databaseBuilder(context,AppDataBase::class.java,"user_db")
.build().also { instance=it }
}
}
}
}
三.数据库Dao类
@Dao //Dao 类声明
interface UserDao {
//这里设置了一下冲突, 如果两条记录相同则会替换
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(user: User)
//这里不需要挂起(返回flow或livedata都不需要)
@Query("