简单使用介绍
- 导包 ```kotlin plugins { … id ‘kotlin-kapt’ }
def room_version = “2.3.0” implementation “androidx.room:room-runtime:$room_version” kapt “androidx.room:room-compiler:$room_version” implementation “androidx.room:room-ktx:$room_version” testImplementation “androidx.room:room-testing:$room_version”
2. 实体类
```kotlin
@Entity(tableName = "user")
class User2(
@PrimaryKey(autoGenerate = true) var id: Long = 0,
@ColumnInfo(name = "user_id")var userId: Long = 0,
@ColumnInfo(name = "user_name") var userName: String,
@ColumnInfo(defaultValue = "china") var address: String,
@Ignore var sex: Boolean
) {
//必须要有构造函数
constructor(): this(0,0,"alice","china",false)
// @PrimaryKey(autoGenerate = true)
// var id: Long = 0
// @ColumnInfo(name = "user_name")
// var userName: String = ""
// @ColumnInfo(defaultValue = "china")
// var address: String = ""
// @Ignore
// var sex: Boolean = false
override fun toString(): String {
return "id = $id ,userid = $userId, userName = $userName , address = $address, sex = $sex"
}
}
Dao 类 ```kotlin @Dao interface UserDao { @Query(“select * from user”) fun queryAll(): List
@Query(“select * from user where id = :id”) fun queryById(id: Long): User2
@Query(“select * from user”) fun queryAll3(): LiveData
- >
@Insert(onConflict = OnConflictStrategy.REPLACE) fun addUser(user2: User2)
@Delete fun delete(user2: User2)
@Query(“delete from user where id = :id”) fun deleteById(id: Long)
@Query(“delete from user”) fun deleteAll()
@Update fun update(user2: User2)
@Query(“update user set user_name = :updateName where id = :id”) fun updateOne(id: Long, updateName: String)
}
4. DataBase 类
```kotlin
@Database(entities = [User2::class], version = 2)
abstract class UserDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
private var instance: UserDatabase? = null
fun getInstance(context: Context): UserDatabase {
if (instance == null) {
instance = Room.databaseBuilder(context, UserDatabase::class.java, "user.db")
.addMigrations(object : Migration(1,2){//数据库升级
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE user "
+ " ADD COLUMN user_id Long NOT NULL DEFAULT 0")
}
})
.allowMainThreadQueries().build()
}
return instance!!
}
}
}
使用示例
class RoomActivity: AppCompatActivity(R.layout.activity_room) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//使用
val userDao = UserDatabase.getInstance(this).userDao()
btnRoomCreate.setOnClickListener {
for (i in 0..9){
val user = User2(userId = i.toLong(),userName = "name$i",address = "address$i",sex = true)
userDao.addUser(user)
}
}
btnRoomQuery.setOnClickListener {
//简单查询所有
val list = userDao.queryAll()
list.forEach {
Log.e(TAG, "onCreate: $it")
}
//使用 livedata 查询和使用 flow 效果一样
//返回livedata,新增的瞬间立马就会监听到,不适合用在查询,适合用在监听上
userDao.queryAll3().observe(this){
Log.e(TAG, "live-onCreate: $it")
}
}
btnRoomQuery2.setOnClickListener {
val user = userDao.queryById(8)
Log.e(TAG, "onCreate: $user")
}
btnRoomAdd.setOnClickListener {
val user = User2(userName = "add",address = "add address",sex = true)
userDao.addUser(user)
}
btnRoomUpdate.setOnClickListener {
userDao.updateOne(8,"hello")
}
btnRoomUpdate2.setOnClickListener {
val user = User2(id = 7,userName = "7777",address = "7777 address",sex = true)
userDao.update(user)
}
btnRoomDelete.setOnClickListener {
userDao.deleteAll()
}
btnRoomDelete2.setOnClickListener {
userDao.deleteById(8)
}
}
}
参考