配置

在根目录的build.gradleplugin下添加

1
id 'com.google.devtools.ksp' version '1.8.21-1.0.11' apply false

注意,版本号1.8.21要与org.jetbrains.kotlin.android版本号一致。示例:

/build.gradle

1
2
3
4
5
6
plugins {
id 'com.android.application' version '8.0.1' apply false
id 'com.android.library' version '8.0.1' apply false
id 'org.jetbrains.kotlin.android' version '1.8.21' apply false
id 'com.google.devtools.ksp' version '1.8.21-1.0.11' apply false
}

app/build.gradle下添加

1
2
3
4
5
6
7
8
9
10
11
def room_version = "2.5.0"

implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"

// To use Kotlin Symbol Processing (KSP)
ksp "androidx.room:room-compiler:$room_version"


// optional - Test helpers
testImplementation "androidx.room:room-testing:$room_version"

将jvm版本改为17

1
2
3
4
5
6
7
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = '17'
}

示例: app/build.gradle

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63

plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'com.google.devtools.ksp'
}


android {
namespace 'com.xyl.roomdemo'
compileSdk 33

defaultConfig {
applicationId "com.xyl.roomdemo"
minSdk 24
targetSdk 33
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = '17'
}
}


dependencies {

implementation 'androidx.core:core-ktx:1.10.1'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.9.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'

def room_version = "2.5.0"

implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"

// To use Kotlin Symbol Processing (KSP)
ksp "androidx.room:room-compiler:$room_version"


// optional - Test helpers
testImplementation "androidx.room:room-testing:$room_version"



}

使用

创建数据库抽象类

AppDataBase.kt

1
2
3
4
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase(){
abstract fun userDao(): UserDao
}

创建entity类

User.kt

1
2
3
4
5
6
@Entity
data class User (
@PrimaryKey val uid: Int,
@ColumnInfo(name = "name") val name: String?,
@ColumnInfo(name = "sex") val sex: String?
)

创建Dao类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.xyl.roomdemo.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.xyl.roomdemo.entity.User

@Dao
interface UserDao {
@Query("select * from user")
fun getAll(): List<User>
@Query("select * from user where uid = (:queryId)")
fun getUserById(queryId: Int): User
@Insert
fun addUser(user: User)
@Update
fun updateUser(user: User)
@Delete
fun delUser(user: User)

}

配置数据库

App.kt

1
2
3
4
5
6
7
8
9
10
11
class App: Application() {
lateinit var db: AppDatabase
override fun onCreate() {
super.onCreate()
Log.i(TAG, "onCreate: app启动")
GlobalScope.launch(Dispatchers.IO) {
db = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "database-name")
.build()
}
}
}

使用示例

MainActivity.kt

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
package com.xyl.roomdemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.xyl.roomdemo.entity.User
import com.xyl.roomdemo.utils.TAG
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val app: App = application as App

GlobalScope.launch(Dispatchers.IO) {
val dao = app.db.userDao()
dao.addUser(User(1001, "小明", "男"))
dao.addUser(User(1002, "小红", "女"))
dao.addUser(User(1003, "小花", "女"))
dao.addUser(User(1004, "张三", "男"))
dao.delUser(User(1002, "", ""))
val userList = dao.getAll()
withContext(Dispatchers.Main) {
Log.i(TAG, "onCreate: ${userList.toString()}")
}

}

}
}

参考文档

https://developer.android.com/training/data-storage/room?hl=zh-cn#setup