網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
一、簡(jiǎn)介
Room 是 Google 官方推出的數(shù)據(jù)庫(kù) ORM 框架。ORM 是指 Object Relational Mapping
,即對(duì)象關(guān)系映射,也就是將關(guān)系型數(shù)據(jù)庫(kù)映射為面向?qū)ο蟮恼Z(yǔ)言。使用 ORM 框架,我們就可以用面向?qū)ο蟮乃枷氩僮麝P(guān)系型數(shù)據(jù)庫(kù),不再需要編寫 SQL 語(yǔ)句。
二、導(dǎo)入
apply plugin: 'kotlin-kapt' dependencies { ... implementation 'androidx.room:room-runtime:2.2.5' kapt 'androidx.room:room-compiler:2.2.5' }
三、使用
Room 的使用可以分為三步:
創(chuàng)建 Entity 類:也就是實(shí)體類,每個(gè)實(shí)體類都會(huì)生成一個(gè)對(duì)應(yīng)的表,每個(gè)字段都會(huì)生成對(duì)應(yīng)的一列。
創(chuàng)建 Dao 類:Dao 是指 Data Access Object
,即數(shù)據(jù)訪問對(duì)象,通常我們會(huì)在這里封裝對(duì)數(shù)據(jù)庫(kù)的增刪改查操作,這樣的話,邏輯層就不需要和數(shù)據(jù)庫(kù)打交道了,只需要使用 Dao 類即可。
創(chuàng)建 Database 類:定義數(shù)據(jù)庫(kù)的版本,數(shù)據(jù)庫(kù)中包含的表、包含的 Dao 類,以及數(shù)據(jù)庫(kù)升級(jí)邏輯。
3.1 創(chuàng)建 Entity 類
新建一個(gè) User 類,并添加 @Entity
注解,使 Room 為此類自動(dòng)創(chuàng)建一個(gè)表。在主鍵上添加 @PrimaryKey(autoGenerate = true)
注解,使得 id 自增,不妨將這里的主鍵 id 記作固定寫法。
@Entity data class User(var firstName: String, var lastName: String, var age: Int) { @PrimaryKey(autoGenerate = true) var id: Long = 0 }
3.2 創(chuàng)建 Dao 類
創(chuàng)建一個(gè)接口類 UserDao,并在此類上添加 @Dao
注解。增刪改查方法分別添加 @Insert
、@Delete
、@Update
、@Query
注解,其中,@Query
需要編寫 SQL 語(yǔ)句才能實(shí)現(xiàn)查詢。Room 會(huì)自動(dòng)為我們生成這些數(shù)據(jù)庫(kù)操作方法。
@Dao interface UserDao { @Insert fun insertUser(user: User): Long @Update fun updateUser(newUser: User) @Query("select * from user") fun loadAllUsers(): List<User> @Query("select * from User where age > :age") fun loadUsersOlderThan(age: Int): List<User> @Delete fun deleteUser(user: User) @Query("delete from User where lastName = :lastName") fun deleteUserByLastName(lastName: String): Int }
@Query
方法不僅限于查找,還可以編寫我們自定義的 SQL 語(yǔ)句,所以可以用它來(lái)執(zhí)行特殊的 SQL 操作,如上例中的 deleteUserByLastName
方法所示。
3.3 創(chuàng)建 Database 抽象類
新建 AppDatabase 類,繼承自 RoomDatabase
類,添加 @Database
注解,在其中聲明版本號(hào),包含的實(shí)體類。并在抽象類中聲明獲取 Dao 類的抽象方法。
@Database(version = 1, entities = [User::class]) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao companion object { private var instance: AppDatabase? = null @Synchronized fun getDatabase(context: Context): AppDatabase { return instance?.let { it } ?: Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_database") .build() .apply { instance = this } } } }
在 getDatabase 方法中,第一個(gè)參數(shù)一定要使用 applicationContext
,以防止內(nèi)存泄漏,第三個(gè)參數(shù)表示數(shù)據(jù)庫(kù)的名字。
3.4 測(cè)試
布局中只有四個(gè) id 為 btnAdd,btnDelete,btnUpdate,btnQuery 的按鈕,故不再給出布局代碼。
MainActivity 代碼如下:
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val userDao = AppDatabase.getDatabase(this).userDao() val teacher = User("lin", "guo", 66) val student = User("alpinist", "wang", 3) btnAdd.setOnClickListener { thread { teacher.id = userDao.insertUser(teacher) student.id = userDao.insertUser(student) } } btnDelete.setOnClickListener { thread { userDao.deleteUser(student) } } btnUpdate.setOnClickListener { thread { teacher.age = 666 userDao.updateUser(teacher) } } btnQuery.setOnClickListener { thread { Log.d("~~~", "${userDao.loadAllUsers()}") } } } }
每一步操作我們都開啟了一個(gè)新線程來(lái)操作,這是由于數(shù)據(jù)庫(kù)操作涉及到 IO,所以不推薦在主線程執(zhí)行。在開發(fā)環(huán)境中,我們也可以通過 allowMainThreadQueries()
方法允許主線程操作數(shù)據(jù)庫(kù),但一定不要在正式環(huán)境使用此方法。
Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_database") .allowMainThreadQueries() .build()
點(diǎn)擊 btnAdd,再點(diǎn)擊 btnQuery,Log 如下:
~~~: [User(firstName=lin, lastName=guo, age=66), User(firstName=alpinist, lastName=wang, age=3)]
點(diǎn)擊 btnDelete,再點(diǎn)擊 btnQuery,Log 如下:
~~~: [User(firstName=lin, lastName=guo, age=66)]
點(diǎn)擊 btnUpdate,再點(diǎn)擊 btnQuery,Log 如下:
~~~: [User(firstName=lin, lastName=guo, age=666)]
由此可見,我們的增刪改查操作都成功了。
四、數(shù)據(jù)庫(kù)升級(jí)
4.1 簡(jiǎn)單升級(jí)
使用 fallbackToDestructiveMigration()
可以簡(jiǎn)單粗暴的升級(jí),也就是直接丟棄舊版本數(shù)據(jù)庫(kù),然后創(chuàng)建最新的數(shù)據(jù)庫(kù)
Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_database") .fallbackToDestructiveMigration() .build()
注:此方法過于暴力,開發(fā)階段可使用,不可在正式環(huán)境中使用,因?yàn)闀?huì)導(dǎo)致舊版本數(shù)據(jù)庫(kù)丟失。
4.2 規(guī)范升級(jí)
4.2.1 新增一張表
創(chuàng)建 Entity 類
@Entity data class Book(var name: String, var pages: Int) { @PrimaryKey(autoGenerate = true) var id: Long = 0 }
創(chuàng)建 Dao 類
@Dao interface BookDao { @Insert fun insertBook(book: Book) @Query("select * from Book") fun loadAllBooks(): List<Book> }
修改 Database 類:
@Database(version = 2, entities = [User::class, Book::class]) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao abstract fun bookDao(): BookDao companion object { private var instance: AppDatabase? = null private val MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( """ create table Book ( id integer primary key autoincrement not null, name text not null, pages integer not null) """.trimIndent() ) } } @Synchronized fun getDatabase(context: Context): AppDatabase { return instance?.let { it } ?: Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_database") .addMigrations(MIGRATION_1_2) .build() .apply { instance = this } } } }
注:這里的修改有:
- version 升級(jí)
- 將 Book 類添加到 entities 中
- 新增抽象方法 bookDao
- 創(chuàng)建
Migration
對(duì)象,并將其添加到 getDatabase 的 builder 中
現(xiàn)在如果再操作數(shù)據(jù)庫(kù),就會(huì)新增一張 Book 表了。
4.2.2 修改一張表
比如在 Book 中新增 author 字段
@Entity data class Book(var name: String, var pages: Int, var author: String) { @PrimaryKey(autoGenerate = true) var id: Long = 0 }
修改 Database,增加版本 2 到 3 的遷移邏輯:
@Database(version = 3, entities = [User::class, Book::class]) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao abstract fun bookDao(): BookDao companion object { private var instance: AppDatabase? = null private val MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( """ create table Book ( id integer primary key autoincrement not null, name text not null, pages integer not null) """.trimIndent() ) } } private val MIGRATION_2_3 = object : Migration(2, 3) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( """ alter table Book add column author text not null default "unknown" """.trimIndent() ) } } @Synchronized fun getDatabase(context: Context): AppDatabase { return instance?.let { it } ?: Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_database") .addMigrations(MIGRATION_1_2, MIGRATION_2_3) .build() .apply { instance = this } } } }
注:這里的修改有:
version 升級(jí)創(chuàng)建 Migration
對(duì)象,并將其添加到 getDatabase 的 builder 中
4.3 測(cè)試
修改 MainActivity:
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val bookDao = AppDatabase.getDatabase(this).bookDao() btnAdd.setOnClickListener { thread { bookDao.insertBook(Book("第一行代碼", 666, "guolin")) } } btnQuery.setOnClickListener { thread { Log.d("~~~", "${bookDao.loadAllBooks()}") } } } }
點(diǎn)擊 btnAdd,再點(diǎn)擊 btnQuery,Log 如下:
~~~: [Book(name=第一行代碼, pages=666, author=guolin)]
這就說(shuō)明我們對(duì)數(shù)據(jù)庫(kù)的兩次升級(jí)都成功了。
參考文章
《第一行代碼》(第三版)- 第 13 章 13.5 Room
原文鏈接:https://blog.csdn.net/AlpinistWang/article/details/106365864
相關(guān)推薦
- 2022-11-14 深度強(qiáng)化學(xué)習(xí)預(yù)訓(xùn)練,在線、離線
- 2022-09-18 K8s實(shí)戰(zhàn)教程之容器和?Pods資源分配問題_云其它
- 2022-08-28 redis 主從同步部署
- 2022-04-28 shell?腳本中獲取命令的輸出的實(shí)現(xiàn)示例_linux shell
- 2022-05-05 R語(yǔ)言因子類型的實(shí)現(xiàn)_R語(yǔ)言
- 2022-04-16 C#算法之實(shí)現(xiàn)阿姆斯特朗數(shù)_C#教程
- 2023-01-17 pytorch?geometric的GNN、GCN的節(jié)點(diǎn)分類方式_python
- 2022-12-24 Docker自定義網(wǎng)絡(luò)詳解_docker
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支