首先要使用Room,需要在app/build.gradle文件中添加如下依赖:
apply plugin: 'kotlin-kapt'
dependencies {
...
implementation "androidx.room:room-runtime:2.2.5"
kapt "androidx.room:room-compiler:2.2.5"
}
实体类的声明:
@Entity
data class UserInfo(var nikeName: String, var gender: Int, var phone: String, var age: Int) {
@PrimaryKey(autoGenerate = true)
var id: Long = 0
}
创建Dao接口:
@Dao
interface UserInfoDao {
@Insert
fun insertUserInfo(userInfo: UserInfo): Long
@Update
fun updateUserInfo(newInfo: UserInfo)
@Query("select * from UserInfo")
fun loadAllUsersInfo(): List<UserInfo>
@Query("select * from UserInfo where age>:age")
fun loadUserInfoOrderThan(age: Int): List<UserInfo>
@Delete
fun deleteUserInfo(user: UserInfo)
@Query("delete from UserInfo where nikeName=:nikeName")
fun deleteByNikeName(nikeName: String): Int
}
定义Database:
@Database(version = 1, entities = [UserInfo::class])
abstract class AppDatabase : RoomDatabase() {
abstract fun userInfoDao(): UserInfoDao
companion object {
private var instance: AppDatabase? = null
@Synchronized
fun getDatabase(context: Context): AppDatabase {
instance?.let { return it }
return Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_database").build()
.apply {
instance = this
}
}
}
}
简单粗暴式数据库升级:
Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_database")
.fallbackToDestructiveMigration()
.build()
不销毁原有数据的升级方式:
@Database(version = 2, entities = [UserInfo::class,Book::class])
abstract class AppDatabase : RoomDatabase() {
abstract fun userInfoDao(): UserInfoDao
abstract fun bookDao(): BookDao
companion object {
private var instance: AppDatabase? = null
val migration_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("create table Book(id integer primary key autoincrement not null,name text not null,pages integer not null)")
}
}
@Synchronized
fun getDatabase(context: Context): AppDatabase {
instance?.let { return it }
return Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_database")
.addMigrations(migration_1_2)
.build()
.apply {
instance = this
}
}
}
}
插入数据的例子:
val userInfoDao = AppDatabase.getDatabase(this).userInfoDao()
val user1 = UserInfo("hyjiao", 0, "18600000000", 25)
thread {
user1.id = userInfoDao.insertUserInfo(user1)
}