0%

Room入门

使用

By default, to avoid poor UI performance, Room doesn’t allow you to issue queries on the main thread. When Room queries return LiveData, the queries are automatically run asynchronously on a background thread.

为避免糟糕的 UI 性能,Room 不允许你在主线程查询数据库。但当查询返回 LiveData 时,查询将自动异步运行在后台线程。

示例

@Entity

1
2
3
4
5
6
@Entity(tableName = "word_table")
data class Word(
@PrimaryKey
@ColumnInfo(name = "word")
val word: String
)

@Dao

1
2
3
4
5
6
7
8
9
10
11
12
@Dao
interface WordDao {

@Query("SELECT * from word_table ORDER BY word ASC")
fun getAlphabetizedWords() :LiveData<List<Word>>

@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(word: Word)

@Query("DELETE FROM word_table")
suspend fun deleteAll()
}

@Database

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
39
40
41
42
43
44
45
46
47
48
49
@Database(entities = [Word::class], version = 1, exportSchema = false)
abstract class WordRoomDatabase : RoomDatabase() {

abstract fun wordDao(): WordDao

companion object {
private var INSTANCE: WordRoomDatabase? = null

fun getDatabase(
context: Context,
scope: CoroutineScope
): WordRoomDatabase {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
WordRoomDatabase::class.java,
"word_database"
)
.addCallback(WordDatabaseCallback(scope))
.build()
INSTANCE = instance
return instance
}
}
}

private class WordDatabaseCallback(val scope: CoroutineScope) : RoomDatabase.Callback() {
override fun onOpen(db: SupportSQLiteDatabase) {
super.onOpen(db)
INSTANCE?.let { database ->
scope.launch {
populateDatabase(database.wordDao())
}
}
}

suspend fun populateDatabase(wordDao: WordDao) {
wordDao.deleteAll()

var word = Word("Hello")
wordDao.insert(word)
word = Word("World")
wordDao.insert(word)
}
}

Repository

1
2
3
4
5
6
7
class WordRepository(private val wordDao: WordDao) {
val allWords = wordDao.getAlphabetizedWords()

suspend fun insert(word: Word) {
wordDao.insert(word)
}
}