Android開發(fā)Jetpack組件Room用例講解
一、簡介
Room 是 Google 官方推出的數(shù)據(jù)庫 ORM 框架。ORM 是指 Object Relational Mapping,即對象關(guān)系映射,也就是將關(guān)系型數(shù)據(jù)庫映射為面向?qū)ο蟮恼Z言。使用 ORM 框架,我們就可以用面向?qū)ο蟮乃枷氩僮麝P(guān)系型數(shù)據(jù)庫,不再需要編寫 SQL 語句。
二、導(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è)對應(yīng)的表,每個(gè)字段都會(huì)生成對應(yīng)的一列。
創(chuàng)建 Dao 類:Dao 是指 Data Access Object,即數(shù)據(jù)訪問對象,通常我們會(huì)在這里封裝對數(shù)據(jù)庫的增刪改查操作,這樣的話,邏輯層就不需要和數(shù)據(jù)庫打交道了,只需要使用 Dao 類即可。
創(chuàng)建 Database 類:定義數(shù)據(jù)庫的版本,數(shù)據(jù)庫中包含的表、包含的 Dao 類,以及數(shù)據(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 語句才能實(shí)現(xiàn)查詢。Room 會(huì)自動(dòng)為我們生成這些數(shù)據(jù)庫操作方法。
@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 語句,所以可以用它來執(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ù)庫的名字。
3.4 測試
布局中只有四個(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è)新線程來操作,這是由于數(shù)據(jù)庫操作涉及到 IO,所以不推薦在主線程執(zhí)行。在開發(fā)環(huán)境中,我們也可以通過 allowMainThreadQueries() 方法允許主線程操作數(shù)據(jù)庫,但一定不要在正式環(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ù)庫升級
4.1 簡單升級
使用 fallbackToDestructiveMigration() 可以簡單粗暴的升級,也就是直接丟棄舊版本數(shù)據(jù)庫,然后創(chuàng)建最新的數(shù)據(jù)庫
Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_database") .fallbackToDestructiveMigration() .build()
注:此方法過于暴力,開發(fā)階段可使用,不可在正式環(huán)境中使用,因?yàn)闀?huì)導(dǎo)致舊版本數(shù)據(jù)庫丟失。
4.2 規(guī)范升級
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 升級
- 將 Book 類添加到 entities 中
- 新增抽象方法 bookDao
- 創(chuàng)建
Migration對象,并將其添加到 getDatabase 的 builder 中
現(xiàn)在如果再操作數(shù)據(jù)庫,就會(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 升級創(chuàng)建 Migration 對象,并將其添加到 getDatabase 的 builder 中
4.3 測試
修改 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)]
這就說明我們對數(shù)據(jù)庫的兩次升級都成功了。
參考文章
《第一行代碼》(第三版)- 第 13 章 13.5 Room
以上就是Android Jetpack組件Room用例講解的詳細(xì)內(nèi)容,更多關(guān)于Android Jetpack組件Room的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Android 自定義View之倒計(jì)時(shí)實(shí)例代碼
這篇文章主要介紹了Android 自定義View之倒計(jì)時(shí)實(shí)例代碼的相關(guān)資料,大多數(shù)app在注冊的時(shí)候,都有一個(gè)獲取驗(yàn)證碼的按鈕,點(diǎn)擊后,訪問接口,最終用戶會(huì)收到短信驗(yàn)證碼。為了不多次寫這個(gè)獲取驗(yàn)證碼的接口,下面將它自定義成一個(gè)view,方便使用,需要的朋友可以參考下2017-04-04
Android apk 插件啟動(dòng)內(nèi)存釋放問題
這篇文章主要介紹了Android apk 插件啟動(dòng)內(nèi)存釋放問題的相關(guān)資料,需要的朋友可以參考下2017-06-06
如何通過Android Logcat插件分析firebase崩潰問題
android crash Crash(應(yīng)用崩潰)是由于代碼異常而導(dǎo)致App非正常退出,導(dǎo)致應(yīng)用程序無法繼續(xù)使用,所有工作都停止的現(xiàn)象,本文重點(diǎn)介紹如何通過Android Logcat插件分析firebase崩潰問題,感興趣的朋友一起看看吧2024-01-01
Android開發(fā)中使用mms模塊收發(fā)單卡和雙卡短信的教程
這篇文章主要介紹了Android開發(fā)中使用mms模塊收發(fā)單卡和雙卡短信的教程,文中舉了MOTO XT800手機(jī)(估計(jì)已經(jīng)落伍很久了--)的例子來說明如何解決雙卡雙待時(shí)的短信異常問題,需要的朋友可以參考下2016-02-02
Android編程實(shí)現(xiàn)為ListView創(chuàng)建上下文菜單(ContextMenu)的方法
這篇文章主要介紹了Android編程實(shí)現(xiàn)為ListView創(chuàng)建上下文菜單(ContextMenu)的方法,簡單分析了上下文菜單的功能及ListView創(chuàng)建上下文菜單(ContextMenu)的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-02-02
Android開發(fā)筆記之:Log圖文詳解(Log.v,Log.d,Log.i,Log.w,Log.e)
本篇文章是對Android中的Log進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
Android標(biāo)題欄最右邊添加按鈕的實(shí)例
這篇文章主要介紹了Android標(biāo)題欄最右邊添加按鈕的實(shí)例的相關(guān)資料,希望通過本文大家能掌握如何操作,需要的朋友可以參考下2017-09-09

