客房软件

Note: This article is part of the advanced Room series which covers all the details about the Room persistence library. You can read all the articles here:

注意:本文是高级Room系列的一部分,该系列涵盖有关Room持久性库的所有详细信息。 您可以在此处阅读所有文章:

  • Introduction to Room Persistent Library in Android

    Android中的房间永久库简介

  • Data Access Objects — DAO in Room

    数据访问对象-房间中的DAO

  • Entity Relationship in Room

    房间中的实体关系

  • How does Room work internally? [You are here]

    客房内部如何运作? [你在这里]

  • Room Database Migrations

    会议室数据库迁移

  • Using Room with LiveData and other third-party libraries

    将Room与LiveData和其他第三方库一起使用

客房内部如何运作? (How Room works internally?)

In the previous articles, we discussed how we can use Room library (part of Google’s Jetpack project) to create relational persistence in Android applications. Room makes it very easy for a developer to setup a database and start using it in production.

在先前的文章中,我们讨论了如何使用Room库(Google Jetpack项目的一部分)在Android应用程序中创建关系持久性。 Room使开发人员可以非常轻松地设置数据库并开始在生产中使用它。

In this article, we are going to focus on how Room accomplishes all these things.

在本文中,我们将重点介绍Room如何完成所有这些事情。

We are going to use this project as reference for explaining how Room actually does everything. Following are the highlights of our project:

我们将使用该项目作为参考,以解释Room实际如何完成所有工作。 以下是我们项目的重点:

  • It has a single database(UserDatabase) which contains only one table/entity(User).

    它具有单个数据库( UserDatabase ),其中仅包含一个表/实体( User )。

@Database(entities = arrayOf(User::class), version = 1)
abstract class UserDatabase : RoomDatabase() {abstract fun userDao(): UserDao
}
  • User table has 3 columns: uid, first name and last name

    用户表具有3列: uid名字姓氏

@Entity
data class User(@PrimaryKey val uid: Int,@ColumnInfo(name = "first_name") val firstName: String?,@ColumnInfo(name = "last_name") val lastName: String?
)
  • UserDao is the interface through which our application interacts with the database.

    UserDao是我们的应用程序与数据库进行交互的接口。

@Dao
interface UserDao {@Query("SELECT * FROM $USERS_TABLE")fun getAll(): List<User>@Insertfun insertAll(vararg users: User)@Deletefun delete(user: User)
}

房间内部工作 (Internal Working of Room)

After creating a Room Database, the first time you compile your code, Room autogenerates implementation of your @Database and @Dao annotated classes. In the above example, implementation of UserDatabase and UserDao is autogenerated by Room annotation processor.

创建Room数据库后,首次编译代码时,Room会自动生成@Database@Dao注释类的实现。 在上面的示例中,Room注释处理器自动生成UserDatabaseUserDao实现。

Note: You can find the autogenerated code in build/generated/source/kapt/ folder.

注意:您可以在build / generated / source / kapt /文件夹中找到自动生成的代码。

In our example, implementation of UserDatabase is named as UserDatabase_Impl and implementation of UserDao is named as UserDao_Impl. These are the classes where actual processing happens. Let’s discuss both of the implementations individually.

在我们的示例中, UserDatabase实现名为UserDatabase_Impl ,而UserDao实现名为UserDao_Impl 。 这些是实际处理发生的类。 让我们分别讨论两个实现。

UserDatabase_Impl (UserDatabase_Impl)

An overview of UserDatabase_Impl looks like this:

UserDatabase_Impl的概述如下所示:

public final class UserDatabase_Impl extends UserDatabase {private volatile UserDao _userDao;@Overrideprotected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration configuration) {//Implementation}@Overrideprotected InvalidationTracker createInvalidationTracker() {//Implementation}@Overridepublic void clearAllTables() {//Implementation}@Overridepublic UserDao userDao() {//Implementation}
}
  • createOpenHelper() is invoked when you build instance of your database using Room.databaseBuilder().build(). It creates and returns an instance of SupportSQLiteOpenHelper which is a helper class for managing database creation and version management.

    createOpenHelper()是当你使用建立数据库的实例调用Room.databaseBuilder().build() 它创建并返回SupportSQLiteOpenHelper的实例,该实例是用于管理数据库创建和版本管理的帮助程序类。

  • createInvalidationTracker() creates an invalidation tracker which keeps a list of tables modified by queries and notifies its callbacks about these tables.

    createInvalidationTracker()创建一个无效跟踪器,该跟踪器保留由查询修改的表的列表,并通知其有关这些表的回调。

  • clearAllTables() implements the behaviour of deleting data from all the tables of the specified database.

    clearAllTables()实现从指定数据库的所有表中删除数据的行为。

  • userDao() creates(if not exists) and returns the instance of UserDao_Impl for interacting with the users table.

    userDao()创建(如果不存在)并返回UserDao_Impl的实例以与users表进行交互。

UserDao_Impl (UserDao_Impl)

UserDao_Impl implements all the methods in UserDao. The overview of UserDao_Impl looks like this:

UserDao_Impl在UserDao中实现所有方法。 UserDao_Impl的概述如下所示:

public final class UserDao_Impl implements UserDao {private final RoomDatabase __db;private final EntityInsertionAdapter<User> __insertionAdapterOfUser;private final EntityDeletionOrUpdateAdapter<User> __deletionAdapterOfUser;public UserDao_Impl(RoomDatabase __db) {this.__db = __db;this.__insertionAdapterOfUser = new EntityInsertionAdapter<User>(__db) {//Implementation};this.__deletionAdapterOfUser = new EntityDeletionOrUpdateAdapter<User>(__db) {//Implementation};}@Overridepublic void insertAll(final User... users) {//Implementation}@Overridepublic void delete(final User user) {//Implementation}@Overridepublic List<User> getAll() {//Implementation}@Overridepublic List<User> loadAllByIds(final int[] userIds) {//Implementation}@Overridepublic User findByName(final String first, final String last) {//Implementation}
}

In the above example, UserDao_Impl has 3 fields: __db, __insertionAdapterOfUser and __deletionAdapterOfUser.

在上述例子中, UserDao_Impl有3个域:__db,__insertionAdapterOfUser__deletionAdapterOfUser。

  • __db is an instance of RoomDatabase which is used for multiple purposes like transaction and querying the database.

    __db是被用于多种目的,如事务,并查询数据库RoomDatabase的一个实例。

  • __insertionAdapterOfUser is an instance of EntityInsertionAdapter used for inserting entities into a table. This is used in insertAll() method.

    __insertionAdapterOfUser是用于插入实体到表EntityInsertionAdapter的一个实例。 这在insertAll()方法中使用。

  • __deletionAdapterOfUser is an instance of EntityDeletionOrUpdateAdapter used to update/delete entities from a table. This is used in delete() method.

    __deletionAdapterOfUserEntityDeletionOrUpdateAdapter的实例,用于从表中更新/删除实体。 这在delete()方法中使用。

建立RoomDatabase (Building the RoomDatabase)

Till now, we have understood what happens after our project is successfully compiled. Also we know that we need an instance of UserDatabase which gives us an instance of UserDao in order to perform any database related operations.

到目前为止,我们已经了解了成功编译项目后会发生什么。 我们也知道我们需要一个UserDatabase实例,该实例为我们提供UserDao实例,以便执行任何与数据库相关的操作。

To get an instance of UserDatabase, Room provides us a builder method named Room.databaseBuilder which gives us an instance of RoomDatabase.Builder. We can use this instance to get UserDatabase by invoking the build() method.

为了获得UserDatabase,的实例UserDatabase, Room为我们提供了一个名为Room.databaseBuilder的构建器方法,该方法为我们提供了RoomDatabase.Builder的实例。 我们可以通过调用build()方法使用此实例获取UserDatabase

val db = Room.databaseBuilder(applicationContext,UserDatabase::class.java, "users-db").build()

We can use this builder to configure our database like

我们可以使用此构建器来配置我们的数据库,例如

  • createFromAsset()/createFromFile() to create and open database from an asset(located in the application ‘assets/’ folder)/a pre-packaged database file.

    createFromAsset() / createFromFile()以从资产(位于应用程序“ assets /”文件夹中)/预打包的数据库文件创建和打开数据库。

  • addMigrations() to add database migration from one version to another. A migration is needed whenever we are changing the version of our database even if there is no change in schema of both versions.

    addMigrations()添加从一个版本到另一个版本的数据库迁移。 每当我们更改数据库版本时,即使两个版本的架构都没有更改,也都需要进行迁移。

  • allowMainThreadQueries() to allow making database queries from main thread. By default, Room doesn’t allow this.

    allowMainThreadQueries()允许从主线程进行数据库查询。 默认情况下,“房间”不允许这样做。

  • fallbackToDestructiveMigration() allows Room to destructively recreate database tables if migration is not found.

    fallbackToDestructiveMigration()允许Room在找不到迁移的情况下以破坏性方式重新创建数据库表。

There are also many other methods provided in RoomDatabase.Builder for database configuration.

RoomDatabase.Builder还提供了许多其他方法来配置数据库。

Once we invoke build() method on thisRoomDatabase.Builder instance, Room validates and creates an instance of the autogenerated implementation of UserDatabase::class.java — i.e., UserDatabase_Impl. After the creation of UserDatabase_Impl, init() method is invoked on the database by passing the database configuration which in turn invokes the createOpenHelper() method of UserDatabase_Impl.

一旦我们在此RoomDatabase.Builder实例上调用build()方法,Room就会验证并创建UserDatabase:: class .java (即UserDatabase_Impl的自动生成的实现的实例。 创建UserDatabase_Impl ,通过传递数据库配置在数据库上调用init()方法,该数据库配置又调用UserDatabase_ImplcreateOpenHelper()方法。

Now we are going to discuss the implementation of some important methods in UserDatabase_Impl and UserDao_Impl discussed earlier.

现在,我们将讨论前面讨论的UserDatabase_Impl和UserDao_Impl中一些重要方法的实现。

UserDatabase_Impl userDao() (userDao() in UserDatabase_Impl)

@Overridepublic UserDao userDao() {  if (_userDao != null) {    return _userDao;  } else {    synchronized(this) {      if(_userDao == null) {        _userDao = new UserDao_Impl(this);      }      return _userDao;    }  } }

It lazily creates the implementation of UserDao — i.e., UserDao_Impl and returns it whenever userDao() is invoked. As we can see, it passes the instance of RoomDatabase in UserDao_Impl’s constructor.

它懒惰地创建UserDao的实现,即UserDao_Impl ,并在调用userDao()时将其返回。 正如我们所看到的,它通过实例RoomDatabaseUserDao_Impl's构造。

insertAll()中UserDao_Impl (insertAll() in UserDao_Impl)

@Overridepublic void insertAll(final User... users) {  __db.assertNotSuspendingTransaction();  __db.beginTransaction();  try {    __insertionAdapterOfUser.insert(users);    __db.setTransactionSuccessful();  } finally {    __db.endTransaction();  }}

It uses __db for creating the transaction and __insertionAdapterOfUser for insertion.

它采用__db用于创建插入交易和__insertionAdapterOfUser。

UserDao_Impl delete() (delete() in UserDao_Impl)

@Overridepublic void delete(final User user) {  __db.assertNotSuspendingTransaction();  __db.beginTransaction();  try {    __deletionAdapterOfUser.handle(user);    __db.setTransactionSuccessful();  } finally {    __db.endTransaction();  }}

It uses __db for creating the transaction and __deletionAdapterOfUser for deletion.

它采用__db用于创建缺失的交易和__deletionAdapterOfUser。

UserDao_Impl getAll() (getAll() in UserDao_Impl)

@Overridepublic List<User> getAll() {  final String _sql = "SELECT * FROM users";  final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);  __db.assertNotSuspendingTransaction();  final Cursor _cursor = DBUtil.query(__db, _statement, false, null);  try {    final int _cursorIndexOfUid = CursorUtil.getColumnIndexOrThrow(_cursor, "uid");    final int _cursorIndexOfFirstName = CursorUtil.getColumnIndexOrThrow(_cursor, "first_name");    final int _cursorIndexOfLastName = CursorUtil.getColumnIndexOrThrow(_cursor, "last_name");    final List<User> _result = new ArrayList<User>(_cursor.getCount());    while(_cursor.moveToNext()) {      final User _item;      final int _tmpUid;      _tmpUid = _cursor.getInt(_cursorIndexOfUid);      final String _tmpFirstName;      _tmpFirstName = _cursor.getString(_cursorIndexOfFirstName);      final String _tmpLastName;      _tmpLastName = _cursor.getString(_cursorIndexOfLastName);      _item = new User(_tmpUid,_tmpFirstName,_tmpLastName);      _result.add(_item);    }    return _result;  } finally {    _cursor.close();    _statement.release();  }}

As we can see, it creates a RoomSQLiteQuery object from the query specified in @Query annotation. It then simply creates a cursor to fetch data from the database.

如我们所见,它根据@Query注释中指定的查询创建一个RoomSQLiteQuery对象。 然后,它仅创建一个游标以从数据库中获取数据。

This is enough to get a basic understanding of how Room works internally.

这足以使您对Room内部的工作方式有基本的了解。

Thank you!!!

谢谢!!!

翻译自: https://medium.com/mindorks/how-does-room-work-internally-c17572b03bed

客房软件


http://www.taodudu.cc/news/show-4974919.html

相关文章:

  • 树莓派4B安装联想LJ2605D打印机驱动
  • 兄弟打印机P950NW 非IE浏览器 打印驱动 和谷歌扩展插件
  • 兄弟mfc9140cdn无法识别_兄弟Brother MFC-9140CDN打印机驱动
  • 兄弟mfc9140cdn无法识别_兄弟Brother MFC-9140CDN打印机驱动下载
  • 为了讲清楚Android触摸事件,我“拆了部手机”
  • 1024程序员节 “1024,Hello world狂欢夜”直播晚会即将开启
  • 初次组装台式机-618自营-装机配置单-3000价位中上普通家用型主机
  • 鼠标侧键能改为ctrl吗_垂直鼠标真的能告别鼠标手吗?
  • 局域网文件服务器的搭建
  • nginx搭建静态文件服务器,利用nginx搭建静态资源服务器的方法步骤
  • 企业文件服务器搭建案例
  • Tomcat文件服务器搭建过程详解
  • 有哪些野路子电脑技能让非程序员感到神奇?
  • 《源码阅读》专栏系列开篇 - 当Java工程师的这几年
  • 为什么说一站式移动办公SaaS平台一定是未来!
  • 一站式移动办公SaaS将成为未来企业管理平台的最佳选择
  • 微办公企业邮箱 企业机密安全防护升级
  • 一份很全的路由器默认初始密码集合
  • fast路由器初始密码 TP-Link、D-Link、ipTIME、Tenda/、Fast水星等路由器恢复出厂设置
  • 华为AR1200路由器清空console密码
  • css101路由密码,192.168.100.1初始密码
  • smiles、sdf 小分子可视化展示标记软件DataWarrior、chemdraw;pdf或图片化学分子提取工具StoneMIND | Collector
  • Python开发自定义Web框架
  • 自动控制原理 (一): 基础概念
  • 自动控制原理知识点梳理——5.线性系统的频域分析法
  • 【自动控制系统的基本原理】
  • MathJax 规则
  • MathJax和相关的Latex语法。
  • Hexo引入Mermaid流程图和MathJax数学公式
  • python mathjax_MathJax: 让前端支持数学公式

客房软件_客房内部如何运作?相关推荐

  1. 相对湿度计算软件_空调工程负荷详细计算方法(附有实例)

    七十年代末空调工程负荷用瞬变传热计算代替了稳定传热计算,并且区分了得热和负荷的概念.八十年代出版的所有空调书籍,如空气调节工程.空气调节设计手册.暖通空调常用数据手册.高层建筑空调与节能等皆引用了动态 ...

  2. 勒索软件_使您的团队投入运营,以持续进行勒索软件防御

    勒索软件 5 steps to bootstrap your organization's cyber defenses without security expertise 无需安全专业知识即可引导 ...

  3. 录制电脑屏幕的软件_电脑屏幕录制操作方法,太实用了!

    电脑屏幕录制操作应该怎么做?本期将和大家分享三种电脑屏幕录制的操作方法,适用于win7.win10和mac三种电脑系统,包括windows7系统自带的步骤记录器和windows10操作系统自带的屏幕录 ...

  4. 上网时间监控软件_电脑监控系统软件有哪些作用?主要功能有哪些?

    随着IT技术和互联网的发展,企业开始利用网络办公来降低管理成本.信息化办公给企业带来了高效快捷的同时,机密泄露事件也层出不穷,网络安全问题变得日益严重.正是在这种背景下,以员工计算机上网行为监管为主的 ...

  5. 工程计算软件_同望BIM工程量计算软件—土石方

         天工造价关注我们,给您想要的工程类资讯 复制以下链接,我要参与 https://www.tgcost.com/member/activity/20190705/index.html 推荐阅读 ...

  6. 软件_手把手教vscode配置c++,python开发环境

    原创:软件_手把手教vscode配置c++,python开发环境 之前主用Python作为项目开发语言,将项目迁移到arm边缘盒子上后发现arm的cpu不给力,软件速度低于预期,所以计划将部分程序改为 ...

  7. 软件_搭建rtsp视频推送环境

    原创博客地址:软件_搭建rtsp视频推送环境 live555编译安装启动 编译 1 2 3 4 5 wget http://www.live555.com/liveMedia/public/live5 ...

  8. 软件_视频rtmp,rmvb,h265区别

    原创博客地址: 软件_视频rtmp,rmvb,h265区别 h265,h264 视频压缩算法,原始视频是图片流,意味着[[r,g,b],[r,g,b],,]等等,极其占用空间,所以这种数据只能出现内存 ...

  9. 软件_搭建rtmp视频推送环境,腾讯云,ubuntu16

    原创博客地址:软件_搭建rtmp视频推送环境,腾讯云,ubuntu16 1,安装conda,ffmpeg,nginx,nginx-rtmp-module (建议先修改主机pip,conda的源) 安装 ...

最新文章

  1. 当移动数据分析需求遇到Quick BI
  2. hdu-5794 A Simple Chess(容斥+lucas+dp)
  3. ajax: PopupControlExtender使用
  4. linux oracle停启,linux下Oracle自动启动与停止总结
  5. 私有云Opetstack的创建与运用
  6. 腾讯爬虫python_Python爬虫,爬取腾讯漫画实战
  7. Hibernate中inverse属性与cascade属性
  8. 翁恺老师C语言学习笔记(七)函数
  9. CentOS-6.5-x86_64 最小化安装,已安装包的总数,这些包?
  10. SWPUACM第一届程序设计大赛
  11. clean-css 安装 使用
  12. oracle12c备份和恢复,oracle12C使用RMAN备份和恢复
  13. 计算机表格中格式隐藏了怎么办,excel表格第一列被隐藏起来了怎么办
  14. Linux Command grep
  15. ruby 去除字符空格
  16. In Search of the Holy Grail 寻找圣杯 中文翻译
  17. ASCII码的转换应用:
  18. TP6基础知识【新框架】
  19. 当面试问到自己有哪些缺点应该怎么回答
  20. java 依赖的项目报错_关于eclipse的maven项目Java Build Path中maven依赖报错问题

热门文章

  1. Python3 多线程threading处理xlsx/csv数据
  2. 米思齐的数码管图形化编程
  3. 基于深度学习的高精度家禽猪检测识别系统(PyTorch+Pyside6+YOLOv5模型)
  4. 终于换掉了驾驶证上的丑照!超简单附教程,赶紧收藏!
  5. 《地理信息系统导论》chapter14 视域和流域分析
  6. 《周鸿祎自述:我的互联网方法论》----摘抄
  7. 考研计算机需要学复变函数与积分变换,《复变函数与积分变换》期末考研重点复习试题...
  8. 监控视频分发转发服务器性能,基于视频监控的分发服务器的研究与实现
  9. U盘数据丢失该如何恢复?
  10. iDownsV1.8.4资源素材教程下载类WordPress