三个类搞定数据操作 @Database、@Entity、@Dao
添加依赖
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-android-extensions'
id 'kotlin-kapt'
}
def roomVersion = "2.3.0"
implementation("androidx.room:room-runtime:$roomVersion")
annotationProcessor("androidx.room:room-compiler:$roomVersion")
kapt("androidx.room:room-compiler:$roomVersion")
创建实体类 用@Entity注解
@Entity
class Student() {
//主键,自动增长
@PrimaryKey(autoGenerate = true)
var id: Int = 0
@ColumnInfo(name = "name")//可以加别名,优先级更高,如果加了就是用别名的名称
lateinit var name: String
@ColumnInfo(name = "age")
var age: Int = 0
constructor(name: String,age: Int): this(){
this.name = name
this.age = age
}
}
创建访问数据库的接口类 使用@Dao注解
@Dao
interface StudentDao {
//vararg 可变参数
//void a(Student... args) vs vararg students: Student
@Insert
fun insertStudents(vararg students: Student)
@Update
fun updateStudents(vararg students: Student)
//删除全部
@Query("DELETE FROM student")
fun deleteAllStudents()
//删除
@Delete
fun deleteStudents(vararg students: Student)
@Query("SELECT * FROM student ORDER BY ID DESC")
fun queryAllStudents(): List<Student>
}
数据库 增删改查操作,使用@Database注解
@Database(entities = [Student::class], version = 1)
abstract class StudentDatabase: RoomDatabase() {
abstract fun getStudentDao() : StudentDao
companion object{
private var INSTANCE : StudentDatabase? = null
// Application 这个函数给Application 用
fun getDatabase(context: Context): StudentDatabase?{
if(INSTANCE == null){
INSTANCE = Room.databaseBuilder(context,StudentDatabase::class.java,"student_database.db")
.allowMainThreadQueries()//允许在主线程运行
.build()
}
return INSTANCE
}
//项目中使用这个方法
fun getDatabase(): StudentDatabase? = INSTANCE
}
}