在app的build.gradle文件中,添加Room依赖:
dependencies {
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"
// optional - RxJava support for Room
implementation "androidx.room:room-rxjava2:$room_version"
// optional - Guava support for Room, including Optional and ListenableFuture
implementation "androidx.room:room-guava:$room_version"
// optional - Test helpers
testImplementation "androidx.room:room-testing:$room_version"
}
创建一个Entity类表示从数据库中检索的表,例如:
@Entity(tableName = "users")
data class User(
@PrimaryKey val id: Int,
@ColumnInfo(name = "name") val name: String?,
@ColumnInfo(name = "age") val age: Int
)
创建一个Dao接口来定义要执行的数据库操作,例如:
@Dao
interface UserDao {
@Query("SELECT * FROM users")
fun getAll(): List
@Query("SELECT * FROM users WHERE id IN (:userIds)")
fun loadAllByIds(userIds: IntArray): List
@Query("SELECT * FROM users WHERE name LIKE :name LIMIT 1")
fun findByName(name: String): User
@Insert
fun insertAll(vararg users: User)
@Delete
fun delete(user: User)
}
创建一个Database类来设置数据库名称、版本和包含的表,例如:
@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
下面是一个使用Room执行数据库操作的示例:
val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "database-name"
).build()
val userDao = db.userDao()
val users = userDao.getAll()