文章目录

  • 一、简介
  • 二、Room使用指南
    • Room使用
    • 验证
    • 结果
  • 三、Room踩坑解答

一、简介

ORM(Object Relational Mapping)关系映射库,在Sqlite上提供了一层封装,优化数据库操作的便捷性。
Room的架构图如下所示:

  • Entity:一个Entity对应于数据库的一张表。Entity类是Sqlite表结构对Java类的映射,在Java中可以被看作一个Model类。
  • Dao:即 Data Access Objects,数据访问对象。顾名思义,我们可以通过它访问对象。

​ 一个Entity对应一张表,而每张表都需要一个Dao对象,用于对表的增删改查。Room对象被实例化之后,我们就可以通过数据库实例得到Dao对象(Get Dao),然后通过Dao对象对表中的数据进行操作。
依赖

buildscript {//android room versionext.room_version = '2.3.0'
}
// room
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
// optional - room kotlin 扩展
implementation "androidx.room:room-ktx:$room_version"

二、Room使用指南

Room使用

通过创建一个简单的学生数据库表,来熟悉Room的基本使用。

  1. 创建一个关于学生的Entity,即创建一张学生表SimpleStudentEntity。

    Entity标签用于将SimpleStudent类与Room中的数据表对应起来。tableName属性可以为数据表设置表名,若不设置,则表名与类名相同。

    PrimaryKey标签用于指定该字段作为表的主键。 autoGenerate = true Set to true to let SQLite generate the unique id.(设置为 true 让 SQLite 生成唯一的 id。)

    ColumnInfo标签可用于设置该字段存储在数据库表中的名字,并指定字段的类型。

    同时为了,其他地方对于表明以及字段相关的引用,我们这里声明为顶层常量(java 的静态常量),方便引用。

    /*** 表名字相关,统一定义.*/
    const val SIMPLE_STUDENT_TABLE_NAME = "simple_student"
    const val SIMPLE_STUDENT_TABLE_STUDENT_ID = "student_id"
    const val SIMPLE_STUDENT_TABLE_STUDENT_NAME = "student_name"
    const val SIMPLE_STUDENT_TABLE_STUDENT_AGE = "student_age"
    

    完整的SimpleStudentEntity.kt文件代码如下所示:

    @Entity(tableName = SIMPLE_STUDENT_TABLE_NAME)
    data class SimpleStudentEntity(@NonNull@PrimaryKey(autoGenerate = true)@ColumnInfo(name = SIMPLE_STUDENT_TABLE_STUDENT_ID,typeAffinity = ColumnInfo.INTEGER) val id: Int = 0,//该值设置为自增的主键,默认会在数据库中自增,这里随便设置一个默认值就可以@NonNull@ColumnInfo(name = SIMPLE_STUDENT_TABLE_STUDENT_NAME, typeAffinity = ColumnInfo.TEXT)val name: String?,@NonNull@ColumnInfo(name = SIMPLE_STUDENT_TABLE_STUDENT_AGE, typeAffinity = ColumnInfo.TEXT)val age: String?
    )
    /*** 表名字相关,统一定义.*/
    const val SIMPLE_STUDENT_TABLE_NAME = "simple_student"
    const val SIMPLE_STUDENT_TABLE_STUDENT_ID = "student_id"
    const val SIMPLE_STUDENT_TABLE_STUDENT_NAME = "student_name"
    const val SIMPLE_STUDENT_TABLE_STUDENT_AGE = "student_age"
    
  2. 针对上面这个学生Entity,我们需要定义一个Dao接口文件,以便对Entity进行访问。注意,在接口文件的上方,需要加入**@Dao**标签。

    增删改查分别使用 Insert、Delete、Update、Query标记。可以在查询前面添加冒号 (:) 来引用查询中的 Kotlin 值(例如,函数参数中的 :id

    查询需要传入sql语句,不了解sql的可以google了解一下。

    @Dao
    interface SimpleStudentDao {@Insertfun insertStudent(studentEntity: SimpleStudentEntity)@Insertfun insertStudentAll(studentEntity: List<SimpleStudentEntity>)@Deletefun deleteStudent(studentEntity: SimpleStudentEntity)@Updatefun updateStudent(studentEntity: SimpleStudentEntity)@Query("select * from $SIMPLE_STUDENT_TABLE_NAME")fun getStudentAll(): List<SimpleStudentEntity>@Query("select * from $SIMPLE_STUDENT_TABLE_NAME where $SIMPLE_STUDENT_TABLE_STUDENT_ID = :id")fun getStudentById(id: Int): List<SimpleStudentEntity>
    }
    
  3. 定义好Entity和Dao后,接下来是创建数据库。
    Database标签用于告诉系统这是Room数据库对象。

    entities属性用于指定该数据库有哪些表,若需要建立多张表,则表名以逗号相隔开。

    version属性用于指定数据库版本号,后面数据库的升级正是依据版本号进行判断的。

    数据库类需要继承自RoomDatabase,并通过Room.databaseBuilder()结合单例设计模式完成创建

    另外,之前创建的Dao对象,在此以抽象方法的形式返回,所以自定义的Database是一个抽象类。

    @Database(entities = arrayOf(SimpleStudentEntity::class), version = 1)
    abstract class SimpleMyDataBase : RoomDatabase() {companion object {private const val DATA_NAME = "simple_db"@Volatileprivate var INSTANCE: SimpleMyDataBase? = null/*** 双重校验锁单例,返回数据库实例*/fun getDataBase(): SimpleMyDataBase = INSTANCE ?: synchronized(this) {val instance = INSTANCE ?: Room.databaseBuilder(AppUtil.application, SimpleMyDataBase::class.java, DATA_NAME).build().also {INSTANCE = it}instance}}/*** 返回 SimpleStudentDao Dao对象*/abstract fun simpleStudentDao(): SimpleStudentDao}
    

验证

以上,数据库和表的创建工作就完成了。下面来看看如何对数据库进行增/删/改/查了吧。

需要注意的是,不能直接在UI线程中执行这些操作,所有操作都需要放在工作线程中进行

写一个Activity,对上面的代码做一些测试。

定义ViewModel文件。Jetpack:ViewModel使用指南,实现原理详细解析!

class SimpleViewModel(private val simpleStudentDao: SimpleStudentDao) : ViewModel() {fun insertStudent(studentEntity: SimpleStudentEntity) {viewModelScope.launch(Dispatchers.Default) {simpleStudentDao.insertStudent(studentEntity)}}fun insertStudentAll(studentEntity: List<SimpleStudentEntity>) {viewModelScope.launch(Dispatchers.Default) {simpleStudentDao.insertStudentAll(studentEntity)}}fun deleteStudent(studentEntity: SimpleStudentEntity) {viewModelScope.launch(Dispatchers.Default) {simpleStudentDao.deleteStudent(studentEntity)}}fun updateStudent(studentEntity: SimpleStudentEntity) {viewModelScope.launch(Dispatchers.Default) {simpleStudentDao.updateStudent(studentEntity)}}suspend fun getStudentAll(): List<SimpleStudentEntity> {//使用主从作用域return supervisorScope {val students = async(Dispatchers.IO) {simpleStudentDao.getStudentAll()}students.await()}}suspend fun getStudentById(id: Int): List<SimpleStudentEntity> {//使用主从作用域return supervisorScope {val students = async(Dispatchers.IO) {simpleStudentDao.getStudentById(id)}students.await()}}override fun onCleared() {super.onCleared()}
}/*** 自定义工厂,可传入Dao参数*/
class MyViewModelFactory(private val dao: SimpleStudentDao) : ViewModelProvider.Factory {override fun <T : ViewModel?> create(modelClass: Class<T>): T {if (modelClass.isAssignableFrom(SimpleViewModel::class.java)) {@Suppress("UNCHECKED_CAST")return SimpleViewModel(dao) as T}throw IllegalArgumentException("Unknown ViewModel class.")}}

Activity

class SimpleRoomDemoActivity : AppCompatActivity() {/*** binding */private var _binding: ActivitySimpleUseRoomBinding? = nullprivate val binding get() = _binding!!/*** 数据库dao*/private val simpleDao: SimpleStudentDao by lazy(LazyThreadSafetyMode.NONE) {SimpleMyDataBase.getDataBase().simpleStudentDao()}/*** viewModel*/lateinit var viewModel: SimpleViewModeloverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)_binding = ActivitySimpleUseRoomBinding.inflate(layoutInflater)setContentView(binding.root)initParam()initView()}private fun initParam() {viewModel = ViewModelProvider(this,//传入自己的工厂MyViewModelFactory(simpleDao))[SimpleViewModel::class.java]}private fun initView() {with(binding) {btnInsert.setOnClickListener {viewModel.insertStudent(SimpleStudentEntity(0, "zxf", "18"))}btnInsertAll.setOnClickListener {viewModel.insertStudentAll(arrayListOf(SimpleStudentEntity(0, "liSi", "18"),SimpleStudentEntity(0, "wangWu", "18")))}//delete 和 update 是根据什么来的  看了源码生成的sql默认根据主键来的btnDelete.setOnClickListener {viewModel.deleteStudent(SimpleStudentEntity(2, "delete", "99"))
//                viewModel.deleteStudent(SimpleStudentEntity(199,"update","99"))}btnUpdate.setOnClickListener {//所以我们这里面可以直接写一个默认的id去设置,不需要非要拿到查询的对象
//                viewModel.updateStudent(SimpleStudentEntity(1,"update","99"))viewModel.updateStudent(SimpleStudentEntity(199, "update", "99"))}//看了一下查询生成的源代码,对于对象来说直接new了,所以不会返回null,但是对象的值,没有就是null,需要声明为可null类型btnGetId.setOnClickListener {lifecycleScope.launch {displayToTextView(viewModel.getStudentById(5))}}btnGetAll.setOnClickListener {lifecycleScope.launch {displayToTextView(viewModel.getStudentAll())}}}}private fun displayToTextView(students: List<SimpleStudentEntity>) {val string = students.joinToString("""""".trimIndent())binding.text.text = string}/*** 释放binding*/override fun onDestroy() {super.onDestroy()_binding = null}
}

结果

三、Room踩坑解答

1.为什么不可以在主线程,进行数据库操作呢?如果非要使用会发生什么?

​ 关于这一点我起初猜想应该和LiveData一样在方法执行的时候,首先对线程做了判断。比如LiveData的setVaule方法,在第一步就判断了,如果不是主线程则抛异常。这个应该也差不多。Jetpack:LiveData使用指南,实现原理详细解析!

​ 我们在生成的Dao实现类里面找一下代码,比如上方我们的Dao接口叫做SimpleStudentDao,通过注解处理器生成了SimpleStudentDao_Impl类,随便找一个方法,比如insert吧,看一下源码:

public void insertStudent(final SimpleStudentEntity studentEntity) {__db.assertNotSuspendingTransaction();__db.beginTransaction();try {__insertionAdapterOfSimpleStudentEntity.insert(studentEntity);__db.setTransactionSuccessful();} finally {__db.endTransaction();}
}

​ 第一个assertNotSuspendingTransaction验证阻塞函数是否处于正确的作用域中(kotlin协程+room造成的事务问题,后面会有文章介绍到,持续关注哈!),如果没有这个验证的话会造成死锁。

​ 看第二个beginTransaction干了什么吧

public void beginTransaction() {assertNotMainThread();...
}
public void assertNotMainThread() {...if (isMainThread()) {throw new IllegalStateException("Cannot access database on the main thread          since it may potentially lock the UI for a long period of time.");}
}

所以不可能在主线程进行数据库操作,否则直接就抛出异常

Jetpack:Room超详细使用踩坑指南!相关推荐

  1. 从无到有 Ubuntu16.04 18.04 20.04安装+Todesk+Chrome+NVIDIA驱动+CUDA+Cudnn+Anaconda3+Pycharm 超详细教程+踩坑问题

    从无到有 Ubuntu16.04 18.04 20.04安装+Todesk+Chrome+NVIDIA驱动+CUDA+Cudnn+Anaconda3+Pycharm 超详细教程+踩坑问题(有部分图片忘 ...

  2. 内网穿透,使用 IPv6 公网访问内网设备踩坑指南

    本文是开启宽带 IPv6 功能并使用公网 IPv6 地址访问内网设备的踩坑指南.IPv6 是目前个人体验最优的内网访问方案,个人体验远胜过 ZeroTier,frp 等方案. 场景 将个人设备暴露于公 ...

  3. pytorch .item_从数据到模型,你可能需要1篇详实的pytorch踩坑指南

    原创 · 作者 | Giant 学校 | 浙江大学 研究方向 | 对话系统.text2sql 熟悉DL的朋友应该知道Tensorflow.Pytorch.Caffe这些成熟的框架,它们让广大AI爱好者 ...

  4. MacBook通过XGP玩女神异闻录5皇家版不踩坑指南

    XGP是微软Xbox游戏通行证服务,全称Xbox Game Pass,俗称西瓜皮. 女神异闻录5皇家版(P5R)登录了全平台,XGP会员可以通过云游戏在MacBook中游玩,本篇为MacBook玩P5 ...

  5. openssl开发库安装时的踩坑指南

    序 前几天用linux编译一个提权脚本的时候报错 openssl/opensslv.h: 没有那个文件或目录 的问题 无论如何也解决不了,这下我记录一个踩坑指南防止下一个人掉进坑里 操作 总体介绍 首 ...

  6. 阿里云天池【Docker练习场】踩坑指南

    阿里云天池[Docker练习场]踩坑指南 题目直达 提交环境搭建(基于macOS) Docker的安装与基本功能使用 Docker安装过程遇到的小问题 提交结果注意事项 提交时的镜像配置 项目结构规范 ...

  7. android手机屏幕共享神器踩坑指南

    开源项目地址:https://github.com/Genymobile/scrcpy scrcpy,由 Genymobile 推出的可跨平台的.可自定义码率的.开源的屏幕共享工具.它提供了在 USB ...

  8. ARouter踩坑指南

    文章目录 ARouter踩坑指南 导读 添加依赖和配置问题 ARouter Helper插件使用问题 Kotlin中使用注解@Autowired获取参数问题 进阶用法通过URL跳转理解 使用withO ...

  9. 【转帖】超详细的 Vagrant 上手指南

    本文转自https://zhuanlan.zhihu.com/p/259833884 超详细的 Vagrant 上手指南 DavyCloud 努力把事讲清楚 91 人赞同了该文章 搭建 Linux 虚 ...

  10. tabbar角标 小程序_【沃行课堂】恭喜你遇到“坑”,小程序踩坑指南

    上周我们的开发小哥哥带领我们一起领略了开发中遇到的各种问题,以及基于SaaS模式的平台技术架构及实现.本周我们换个方向,由高级开发工程师秋哥带领大家共同探讨下小程序开发中踩过的坑.秋哥会从公司的几个小 ...

最新文章

  1. 我是一个SDN控制器
  2. python点到向量的距离,夹角
  3. 20155303 2016-2017-2 《Java程序设计》第四周学习总结
  4. 关于延长物联网设备的生命周期
  5. opencv图像切割1-KMeans方法
  6. linux赋权限2770,Linux权限:SUID,SGID以及粘滞位
  7. P3317 [SDOI2014]重建
  8. 个人介绍网页代码 html静态网页设计制作 dw静态网页成品模板素材网页 web前端网页设计与制作 div静态网页设计
  9. HTML页面跳转及参数传递
  10. php主机卫士,Bypass 360主机卫士SQL注入防御(附tamper脚本)
  11. Technorati.com 被劫持
  12. html css alpha,CSS滤镜之alpha属性-网页设计,HTML/CSS
  13. 什么是最长前缀匹配?为什么网络前缀越长,其地址块就越小,路由就越具体?
  14. excel中将字符转换为数值
  15. 阿里巴巴 镜像下载 centos 镜像下载 Linux镜像下载
  16. 如何让电脑显示SVG图片的缩略图
  17. USB Type C数据线接线方式、工作原理
  18. kali------kali更新源
  19. 使用GSview打开.ps文件
  20. 图形图像处理案例2——勾线画生成器,绕线画生成器

热门文章

  1. C语言求金蝉素数,回文数 - 寂寞暴走伤的个人空间 - OSCHINA - 中文开源技术交流社区...
  2. JS滑动滚动的n种方式
  3. ESP8266开发板刷WI-PWN固件(wifi杀手)教程(详细)
  4. Sails基础之Controller层
  5. Redis集群搭建——新手上路
  6. 最实用的Mysql安全加固手册
  7. 最强的手机文件管理器!
  8. nginx容器通过docker内置DNS实现动态负载
  9. OWASP juice shop靶场闯关题解
  10. 君莫笑系列视频学习(0)