最近在kotlin环境下,写了一个room数据库的demo,各种情况跑了一下,在此总结一下。
涉及情况:增、删、改、查、排序
1、环境搭建
1.1、Android Studio下,新建一个kotlin项目,
1.2、去app的build.gradle中进行一些配置
顶部增加
apply plugin: 'kotlin-kapt'
然后
defaultConfig {
......
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation":
"$projectDir/schemas".toString()]
}
}
}
1.3、导入依赖
implementation 'android.arch.persistence.room:runtime:1.1.1'
kapt 'android.arch.persistence.room:compiler:1.1.1'
2、创建一个Application,用于提供全局上下文
class MyApplication : Application() {
companion object {
var instance: MyApplication by Delegates.notNull()
fun instance() = instance
}
override fun onCreate() {
super.onCreate()
instance = this
}
}
3、分别创建Student和Teacher(我写了2张表)
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
@Entity(tableName = "Student")
data class Student(
@PrimaryKey(autoGenerate = true)
var studentID: Int?,
@ColumnInfo(name = "s_name")
var studentName: String?,
@ColumnInfo(name = "s_type")
var studentType: String?
)
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
@Entity(tableName = "Teacher")
data class Teacher(
@PrimaryKey(autoGenerate = true)
var teacherID: Int?,
@ColumnInfo(name = "t_name")
var teacherName: String?,
//教学年限
@ColumnInfo(name = "t_year")
var teachYear: Int?
)
4、与之对应的,分别创建StudentDao和TeacherDao
import android.arch.persistence.room.*
@Dao
interface BaseDao<T> {
@Insert(onConflict = OnConfl