dependencies {
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-ktx:$room_version"
// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"
// optional - RxJava3 support for Room
implementation "androidx.room:room-rxjava3:$room_version"
// optional - Guava support for Room, including Optional and ListenableFuture
implementation "androidx.room:room-guava:$room_version"
// optional - Testing Room migrations
testImplementation "androidx.room:room-testing:$room_version"
// optional - Paging 3 Integration
implementation "androidx.room:room-paging:2.4.0-alpha02"
}
2.创建一个实体类来表示数据库中的表:
@Entity(tableName = "user")
data class User(
@PrimaryKey val id: Int,
val name: String,
val age: Int
)
3.创建一个 DAO 接口来定义数据访问:
@Dao
interface UserDao {
@Query("SELECT * FROM user")
fun getAll(): List
@Query("SELECT * FROM user WHERE id = :userId")
fun getUserById(userId: Int): User
@Insert
fun insertAll(vararg users: User)
@Delete
fun delete(user: User)
}
4.创建数据库类,并将实体类和 DAO 接口作为参数传递:
@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
5.使用数据库:
val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "database-name"
).build()
val userDao = db.userDao()
val users = userDao.getAll()
val user = userDao.getUserById(1)