特性
1.SQL语句高亮
2. 简单入门
3. 功能强大
4. 数据库监听
5. 支持Kotlin协程/RxJava/Guava
依赖
1 2 3 4 5 6 7 8 9 10 11
| dependencies{ val room_version = "2.2.0-rc01"
implementation("androidx.room:room-runtime:$room_version") annotationProcessor "androidx.room:room-compiler:$room_version"
implementation("androidx.room:room-ktx:$room_version") }
|
使用
ROOM会在创建数据库对象时就会创建好所有已注册的数据表结构
- 创建数据库
- 创建操作接口
- 创建数据类: 一般为JSON反序列出的data class
实体类
1 2 3 4 5 6 7 8 9
| @Entity(tableName = "todo_item") data class ToDoItem( @PrimaryKey(autoGenerate = true) val id: Int = 0, val title: String = "", val date: String = System.currentTimeMillis().toString(), var completed: Boolean = false, var archived: Boolean = false )
|
Dao接口
1 2 3 4 5 6 7 8 9 10 11 12
| @Dao interface ToDoItemDao {
@Query("SELECT * FROM todo_item WHERE archived = 0 ORDER BY id DESC") fun getAll(): List<ToDoItem> @Insert suspend fun insert(toDoItem: ToDoItem):Long
@Update suspend fun update(toDoItem: ToDoItem) }
|
数据库实体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| @Database(entities = [ToDoItem::class], version = 2, exportSchema = false) abstract class RoomDB : RoomDatabase() {
abstract fun ToDoItemDao(): ToDoItemDao companion object { private var INSTANCE: RoomDB? = null
fun getInstance(context: Context): RoomDB { return runBlocking(Dispatchers.IO) { var instance = INSTANCE if (instance == null) { instance = Room.databaseBuilder(context, RoomDB::class.java, "todo_db") .allowMainThreadQueries() .addCallback(DbCreateCallBack()) .addMigrations(MIGARATION_1_2) .build() } instance } } val MIGARATION_1_2 = object : Migration(1, 2) { override fun migrate(db: SupportSQLiteDatabase) { db.execSQL("ALTER TABLE todo_item ADD COLUMN archived INTEGER NOT NULL DEFAULT 0") } }
private fun DbCreateCallBack(): RoomDatabase.Callback { return object : RoomDatabase.Callback() { override fun onCreate(db: SupportSQLiteDatabase) { super.onCreate(db) Log.d("First", "first onCreate db version: " + db.version) } } }
} }
|
DQL
ROOM支持查询函数返回四种类型
- Single/Mabye/Completable/Observable/Flowable 等RxJava的被观察者
- LiveData: JetPack库中的活跃观察者
- Flow: Kotlin协程中的流
- Cursor: SQLite在Android中最原始的查询结果集, 此返回对象无法监听数据库变化
我不再推荐在项目中使用RxJava, 因为无法方便实现并发并且容易产生回调地域. 这里建议使用协程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @Query("select * from Book") fun find(): Flow<Array<Book>>
@Query("select * from Book") fun find(): Observable<Array<Book>>
@Query("select * from Book") fun find(): LiveData<Array<Book>>
@Query("select * from Book") fun find(): LiveData<List<Book>>
@Query("select * from Book") fun find(): Flow<Array<Book>>
@Query("select * from Book") fun find(): Cursor
|
多表查询,1对n,n对n
这一部分内容在前期学习时用的较少,因此需要使用时可以再此学习
直接看这篇文章https://juejin.cn/post/6844904079098036232
该文章借鉴于12