官方文档参考 google官方
val db = Room.databaseBuilder(
this,
DaoFactory::class.java, "application_db_11"
).allowMainThreadQueries()
.build()
val dao = db.StudentDao()
// dao.insertStudent(Student(1, "hello world", "aaa"))
Log.i("studentInfo ", dao.getAll().toString())
实体类:
package com.lyr.myapplication.db.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* @Author lyr
* @create 2020/10/15 14:15
*/
@Entity(tableName = "t_student")
data class Student(
@PrimaryKey
val id: Int,
@ColumnInfo
val studentName: String,
@ColumnInfo
val content: String
)
定义:
package com.lyr.myapplication.db.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.lyr.myapplication.db.entity.Student
/**
* @Author lyr
* @create 2020/10/15 14:26
*/
@Dao
interface StudentDao{
@Query("select * from t_student")
fun getAll():List<Student>
@Insert
fun insertStudent(vararg students:Student)
}
抽象工厂:
package com.lyr.myapplication.db
import androidx.room.Database
import androidx.room.RoomDatabase
import com.lyr.myapplication.db.dao.StudentDao
import com.lyr.myapplication.db.entity.Student
/**
* @Author lyr
* @create 2020/10/15 14:28
*/
@Database(entities = arrayOf(Student::class),version = 1)
abstract class DaoFactory: RoomDatabase (){
abstract fun StudentDao():StudentDao
}