Android開發(fā)Jetpack組件Room用例講解
一、簡介
Room 是 Google 官方推出的數(shù)據(jù)庫 ORM 框架。ORM 是指 Object Relational Mapping
,即對象關系映射,也就是將關系型數(shù)據(jù)庫映射為面向?qū)ο蟮恼Z言。使用 ORM 框架,我們就可以用面向?qū)ο蟮乃枷氩僮麝P系型數(shù)據(jù)庫,不再需要編寫 SQL 語句。
二、導入
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 類:也就是實體類,每個實體類都會生成一個對應的表,每個字段都會生成對應的一列。
創(chuàng)建 Dao 類:Dao 是指 Data Access Object
,即數(shù)據(jù)訪問對象,通常我們會在這里封裝對數(shù)據(jù)庫的增刪改查操作,這樣的話,邏輯層就不需要和數(shù)據(jù)庫打交道了,只需要使用 Dao 類即可。
創(chuàng)建 Database 類:定義數(shù)據(jù)庫的版本,數(shù)據(jù)庫中包含的表、包含的 Dao 類,以及數(shù)據(jù)庫升級邏輯。
3.1 創(chuàng)建 Entity 類
新建一個 User 類,并添加 @Entity
注解,使 Room 為此類自動創(chuàng)建一個表。在主鍵上添加 @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)建一個接口類 UserDao,并在此類上添加 @Dao
注解。增刪改查方法分別添加 @Insert
、@Delete
、@Update
、@Query
注解,其中,@Query
需要編寫 SQL 語句才能實現(xiàn)查詢。Room 會自動為我們生成這些數(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
注解,在其中聲明版本號,包含的實體類。并在抽象類中聲明獲取 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 方法中,第一個參數(shù)一定要使用 applicationContext
,以防止內(nèi)存泄漏,第三個參數(shù)表示數(shù)據(jù)庫的名字。
3.4 測試
布局中只有四個 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()}") } } } }
每一步操作我們都開啟了一個新線程來操作,這是由于數(shù)據(jù)庫操作涉及到 IO,所以不推薦在主線程執(zhí)行。在開發(fā)環(huán)境中,我們也可以通過 allowMainThreadQueries()
方法允許主線程操作數(shù)據(jù)庫,但一定不要在正式環(huán)境使用此方法。
Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_database") .allowMainThreadQueries() .build()
點擊 btnAdd,再點擊 btnQuery,Log 如下:
~~~: [User(firstName=lin, lastName=guo, age=66), User(firstName=alpinist, lastName=wang, age=3)]
點擊 btnDelete,再點擊 btnQuery,Log 如下:
~~~: [User(firstName=lin, lastName=guo, age=66)]
點擊 btnUpdate,再點擊 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)境中使用,因為會導致舊版本數(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ù)庫,就會新增一張 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()}") } } } }
點擊 btnAdd,再點擊 btnQuery,Log 如下:
~~~: [Book(name=第一行代碼, pages=666, author=guolin)]
這就說明我們對數(shù)據(jù)庫的兩次升級都成功了。
參考文章
《第一行代碼》(第三版)- 第 13 章 13.5 Room
以上就是Android Jetpack組件Room用例講解的詳細內(nèi)容,更多關于Android Jetpack組件Room的資料請關注腳本之家其它相關文章!
相關文章
如何通過Android Logcat插件分析firebase崩潰問題
android crash Crash(應用崩潰)是由于代碼異常而導致App非正常退出,導致應用程序無法繼續(xù)使用,所有工作都停止的現(xiàn)象,本文重點介紹如何通過Android Logcat插件分析firebase崩潰問題,感興趣的朋友一起看看吧2024-01-01Android開發(fā)中使用mms模塊收發(fā)單卡和雙卡短信的教程
這篇文章主要介紹了Android開發(fā)中使用mms模塊收發(fā)單卡和雙卡短信的教程,文中舉了MOTO XT800手機(估計已經(jīng)落伍很久了--)的例子來說明如何解決雙卡雙待時的短信異常問題,需要的朋友可以參考下2016-02-02Android編程實現(xiàn)為ListView創(chuàng)建上下文菜單(ContextMenu)的方法
這篇文章主要介紹了Android編程實現(xiàn)為ListView創(chuàng)建上下文菜單(ContextMenu)的方法,簡單分析了上下文菜單的功能及ListView創(chuàng)建上下文菜單(ContextMenu)的具體步驟與相關操作技巧,需要的朋友可以參考下2017-02-02Android開發(fā)筆記之:Log圖文詳解(Log.v,Log.d,Log.i,Log.w,Log.e)
本篇文章是對Android中的Log進行了詳細的分析介紹,需要的朋友參考下2013-05-05