引入依赖
id 'kotlin-kapt'
implementation "androidx.room:room-runtime:2.1.0"
kapt "androidx.room:room-compiler:2.1.0"
Entity实体类
@Entity
data class User(
var firstName: String,
var lastName: String,
var age: Int,
) {
@PrimaryKey(autoGenerate = true)
var id: Long = 0
}
Dao逻辑封装
@Dao
interface UserDao {
@Insert
fun insertUser(user: User): Long
@Update
fun updateUser(user: User)
@Query("select * from User")
fun selectAllUser(): List<User>
@Delete
fun deleteUser(user: User)
@Query("delete from User where lastName = :lastName")
fun deleteUserByLastName(lastName: String)
}
Database提供实例
@Database(version = 1, entities = [User::class])
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
private var instance: AppDatabase? = null
@Synchronized
fun getDatabase(context: Context): AppDatabase {
if (instance == null) {
instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"app_database"
).build()
}
return instance!!
}
}
}
简单使用
val userDao = AppDatabase.getDatabase(this).userDao()
val user1 = User("小", "名", 12)
addButton.setOnClickListener {
thread {
user1.id = userDao.insertUser(user1)
}
}
|