1.首先在app.gradle上方添加
//room数据库
apply plugin: 'kotlin-kapt'
2.添加所需要的库
implementation 'androidx.room:room-runtime:2.2.3'
annotationProcessor 'androidx.room:room-compiler:2.2.3'
kapt 'androidx.room:room-compiler:2.2.3'
androidTestImplementation 'androidx.room:room-testing:2.2.3'
3.创建是实体类User.kt
@Dao
interface UserDao {
@Query("SELECT * FROM Users WHERE userid = :id")
fun getUserById(id: String): User?
/*当数据库中已经有此用户的时候,直接替换*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertUser(user: User)
@Update
fun upDateUser(user: User)
@Query("DELETE FROM Users")
fun deleteAllUsers()
}
4.创建dao文件UserDao.kt
@Dao
interface UserDao {
@Query("SELECT * FROM Users WHERE userid = :id")
fun getUserById(id: String): User?
/*当数据库中已经有此用户的时候,直接替换*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertUser(user: User)
@Update
fun upDateUser(user: User)
@Query("DELETE FROM Users")
fun deleteAllUsers()
}
5.创建AppDatabase.kt
@Database(entities = arrayOf(User::class), version = 1)
abstract class UsersDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
@Volatile
private var INSTANCE: UsersDatabase? = null
fun getInstance(context: Context): UsersDatabase = INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(
context.applicationContext,
UsersDatabase::class.java, "Sample.db")
.build()
}
}
6.使用
UsersDatabase .getInstance(this).userDao().insertUser()