美文网首页
Room使用笔记

Room使用笔记

作者: 紫鹰 | 来源:发表于2020-12-04 10:06 被阅读0次

作用
以下是官方文档

Room 在 SQLite 上提供了一个抽象层,以便在充分利用 SQLite 的强大功能的同时,能够流畅地访问数据库。

处理大量结构化数据的应用可极大地受益于在本地保留这些数据。最常见的用例是缓存相关数据。这样,当设备无法访问网络时,用户仍可在离线状态下浏览相应内容。设备重新连接到网络后,用户发起的所有内容更改都会同步到服务器。

缓存用户操作这种使用场景之前并没有使用过,以后还是要多使用的

简单使用
1.gradle配置

dependencies {
def room_version = "2.2.5"

implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"

// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"

// optional - Test helpers
testImplementation "androidx.room:room-testing:$room_version"

}
2.创建实体

@Entity(tableName = "log_database")
data class LogEntity(
@PrimaryKey(autoGenerate = true) val uid: Int = 0 ,
@ColumnInfo(name = "logTime") val logTime: String?,
@ColumnInfo(name = "messageType") val messageType: Int?,
@ColumnInfo(name = "messageContent") val messageContent: String?
) {

}

几个注解 @Entity 数据库表结构,可以用tableName声明表名,默认为类名,大小写不敏感 @PrimaryKey 主键,可用autoGenerate = true属性交给系统托管

3.创建DAO

@Dao
interface LogDao {

@Insert
fun insertLog(log: LogEntity)

@Query("select * from log_database LIMIT 20")
@Transaction
fun queryDepartLog(): List<LogEntity>

@Delete
fun deleteLog(log : LogEntity)
//批量操作 
@Insert fun insertLogs( logs: List)
}

DAO 用于对数据库的增删改查直接访问

4.编写RoomDataBase

@Database(entities = arrayOf(LogEntity::class), version = 1,exportSchema = false) 
abstract class LogDataBase : RoomDatabase() {

abstract fun logDao(): LogDao


companion object {
  @Volatile
  private var INSTANCE: LogDataBase? = null
  fun getLogDataBase(context: Context): LogDataBase {

    val tempInstance = INSTANCE
    if (tempInstance != null) {
        return tempInstance;
    }

    synchronized(this) {
        val instace = Room.databaseBuilder(context, LogDataBase::class.java, "log_database")
                .build()
        INSTANCE = instace
        return instace
     }
   }
 }

}
Database 指定数据结构,数据库版本,获取DAO实例

ps:database实例获取使用单例模式,并非必须

5.编写Repository(非必须)

class LogDataRepository(private val logDao: LogDao) {

  fun queryDepartLog():List<LogEntity>{
      return logDao.queryDepartLog()
  }

  fun insert(logEntity: LogEntity) {
     logDao.insertLog(logEntity)
  }

  fun deleteLog(logEntity: LogEntity) {
     logDao.deleteLog(logEntity)
  }

}

Repository 常规代码,纯粹是为了封装,方便上层业务与底层数据的解藕

进阶使用
数据关系建立

数据迁移(版本升级)

1.版本号自增

 @Database(entities = arrayOf(LogEntity::class), version = 2,exportSchema = false)
 abstract class LogDataBase : RoomDatabase() {
  }

2.创建Migration

  val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(database: LogDataBase) {
       database.execSQL("ALTER TABLE log_database ADD COLUMN pub_year INTEGER")
     }
   }

3.Room构建配置

     Room.databaseBuilder(context, LogDataBase::class.java, "log_database")
                .addMigrations(MIGRATION_1_2).build()

配合livedata以及kotlin协程使用
几个经典bug

相关文章

网友评论

      本文标题:Room使用笔记

      本文链接:https://www.haomeiwen.com/subject/qcwelftx.html