简单使用介绍

  1. 导包 ```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”

  1. 2. 实体类
  2. ```kotlin
  3. @Entity(tableName = "user")
  4. class User2(
  5. @PrimaryKey(autoGenerate = true) var id: Long = 0,
  6. @ColumnInfo(name = "user_id")var userId: Long = 0,
  7. @ColumnInfo(name = "user_name") var userName: String,
  8. @ColumnInfo(defaultValue = "china") var address: String,
  9. @Ignore var sex: Boolean
  10. ) {
  11. //必须要有构造函数
  12. constructor(): this(0,0,"alice","china",false)
  13. // @PrimaryKey(autoGenerate = true)
  14. // var id: Long = 0
  15. // @ColumnInfo(name = "user_name")
  16. // var userName: String = ""
  17. // @ColumnInfo(defaultValue = "china")
  18. // var address: String = ""
  19. // @Ignore
  20. // var sex: Boolean = false
  21. override fun toString(): String {
  22. return "id = $id ,userid = $userId, userName = $userName , address = $address, sex = $sex"
  23. }
  24. }
  1. 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)

}

  1. 4. DataBase
  2. ```kotlin
  3. @Database(entities = [User2::class], version = 2)
  4. abstract class UserDatabase : RoomDatabase() {
  5. abstract fun userDao(): UserDao
  6. companion object {
  7. private var instance: UserDatabase? = null
  8. fun getInstance(context: Context): UserDatabase {
  9. if (instance == null) {
  10. instance = Room.databaseBuilder(context, UserDatabase::class.java, "user.db")
  11. .addMigrations(object : Migration(1,2){//数据库升级
  12. override fun migrate(database: SupportSQLiteDatabase) {
  13. database.execSQL("ALTER TABLE user "
  14. + " ADD COLUMN user_id Long NOT NULL DEFAULT 0")
  15. }
  16. })
  17. .allowMainThreadQueries().build()
  18. }
  19. return instance!!
  20. }
  21. }
  22. }
  1. 使用示例

    1. class RoomActivity: AppCompatActivity(R.layout.activity_room) {
    2. override fun onCreate(savedInstanceState: Bundle?) {
    3. super.onCreate(savedInstanceState)
    4. //使用
    5. val userDao = UserDatabase.getInstance(this).userDao()
    6. btnRoomCreate.setOnClickListener {
    7. for (i in 0..9){
    8. val user = User2(userId = i.toLong(),userName = "name$i",address = "address$i",sex = true)
    9. userDao.addUser(user)
    10. }
    11. }
    12. btnRoomQuery.setOnClickListener {
    13. //简单查询所有
    14. val list = userDao.queryAll()
    15. list.forEach {
    16. Log.e(TAG, "onCreate: $it")
    17. }
    18. //使用 livedata 查询和使用 flow 效果一样
    19. //返回livedata,新增的瞬间立马就会监听到,不适合用在查询,适合用在监听上
    20. userDao.queryAll3().observe(this){
    21. Log.e(TAG, "live-onCreate: $it")
    22. }
    23. }
    24. btnRoomQuery2.setOnClickListener {
    25. val user = userDao.queryById(8)
    26. Log.e(TAG, "onCreate: $user")
    27. }
    28. btnRoomAdd.setOnClickListener {
    29. val user = User2(userName = "add",address = "add address",sex = true)
    30. userDao.addUser(user)
    31. }
    32. btnRoomUpdate.setOnClickListener {
    33. userDao.updateOne(8,"hello")
    34. }
    35. btnRoomUpdate2.setOnClickListener {
    36. val user = User2(id = 7,userName = "7777",address = "7777 address",sex = true)
    37. userDao.update(user)
    38. }
    39. btnRoomDelete.setOnClickListener {
    40. userDao.deleteAll()
    41. }
    42. btnRoomDelete2.setOnClickListener {
    43. userDao.deleteById(8)
    44. }
    45. }
    46. }

    参考

    SQL基本语句
    Android Jetpack架构组件 — Room入坑详解