implementation "androidx.room:room-runtime:x.x.x"
kapt "androidx.room:room-compiler:x.x.x"
其中,x.x.x为版本号,可以根据自己的需要选择。
@Entity(tableName = "user_table")
data class User (
@PrimaryKey(autoGenerate = true) val id: Int,
val name: String,
val age: Int
)
@Dao
interface UserDao {
@Insert
suspend fun addUser(user: User)
@Update
suspend fun updateUser(user: User)
@Delete
suspend fun deleteUser(user: User)
@Query("SELECT * FROM user_table")
suspend fun getUsers(): List
}
@Database(entities = [User::class], version = 1, exportSchema = false)
abstract class UserDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
@Volatile
private var INSTANCE: UserDatabase? = null
fun getDatabase(context: Context): UserDatabase {
val tempInstance = INSTANCE
if (tempInstance != null) {
return tempInstance
}
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
UserDatabase::class.java,
"user_database"
).build()
INSTANCE = instance
return instance
}
}
}
}