在Kotlin中使用Room數據庫主要有以下幾個步驟:
implementation "androidx.room:room-runtime:2.4.0"
kapt "androidx.room:room-compiler:2.4.0"
@Entity(tableName = "user")
data class User(
@PrimaryKey val id: Int,
val name: String,
val age: Int
)
@Dao
interface UserDao {
@Query("SELECT * FROM user")
fun getAllUsers(): List<User>
@Insert
fun insertUser(user: User)
@Update
fun updateUser(user: User)
@Delete
fun deleteUser(user: User)
}
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "my-database"
).build()
val userDao = db.userDao()
// 使用DAO對象進行數據庫操作
val users = userDao.getAllUsers()
通過以上步驟,您可以在Kotlin中使用Room數據庫進行數據存儲和檢索操作。Room提供了方便的API和注解來簡化數據庫操作,使得數據持久化變得更加簡單和高效。