10分钟学习 Jetpack组件-Room数据库

前言

我会将所有的文章都配套视频进行讲解。因为想通过这样的方式来帮助大家,降低学习成本。我也会邀请其他作者,一起以这种文章加视频的方式进行讲解。同时会发布到公众号上,大家可以关注我的公众号。因为是第一次搞,如果大家有任何问题,提出来,我会尽可能的帮大家解答。

Room数据库的创建

1.添加依赖

话不多说:首先要进行依赖,因为我们使用的是kotlin。
所以根据官网提示,在app model的build.gradle文件的dependencies添加:

dependencies {
  def room_version = "2.2.6"
  implementation "androidx.room:room-runtime:$room_version"
  kapt "androidx.room:room-compiler:$room_version"
  // optional - Kotlin Extensions and Coroutines support for Room
  implementation "androidx.room:room-ktx:$room_version"
}

添加依赖后会报错Could not find method kapt() for arguments。需要添加apply plugin: 'kotlin-kapt'。我会在视频中详细展示。

2.继承RoomDatabase
@Database(
    entities = [Teacher::class],
    version = 1,
    exportSchema = false
)
abstract class BackGardenDatabase : RoomDatabase() {
  abstract fun teacherDao(): TeacherDao //这里是非常重要的一步,后面我们来说 !!!
}
3.创建Teacher类,并使用@Entity注解
@Entity(tableName = "teacher")
class Teacher(
    @PrimaryKey
    val teacherId: String,
    @ColumnInfo(name = "teacher_name")
    val teacherName: String,
    @Embedded
    val student: Student,
)

因为使用到了Student类,

@Entity
class Student(
    @PrimaryKey
    val studentId: String,
    val studentName: String,
)
4.接下来就是比较重要的一步,创建TeacherDao接口,使用@Dao注解。这里就是操作数据库中数据的操作。CRUD(增删改查)。
@Dao
interface TeacherDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun save(teacher: Teacher): Long

    @Query("select * from teacher where `teacherId`=:teacherId")
    fun getTeacher(teacherId: String): Teacher

    @Query("select * from teacher ")
    fun getTeachers(): LiveData>

    @Delete
    fun delete(teacher: Teacher)

    @Update(onConflict = OnConflictStrategy.REPLACE)
    fun update(teacher: Teacher)

    @Query("delete from teacher where `teacherId`=:teacherId")
    fun deleteById(teacherId: String);
}

这时,我们就需要在数据库中声明如下代码:

abstract fun teacherDao(): TeacherDao

到这里我们数据库的准备已经差不多了。接下来就是使用的环节。

Room数据库的使用

1.对外提供数据库类,我们来进行操作
class AppModel {

    val mMigration: Migration by lazy {
        object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("alter table teacher rename to teacher1")
                database.execSQL("alter table teacher1 add column teach_age INTEGER NOT NULL  default 0 ")
            }
        }

    }
    val backGardenDatabase: BackGardenDatabase by lazy {
        Room.databaseBuilder(
            AppGlobals.getApplication(),
            BackGardenDatabase::class.java,
            "back_garden"
        )
            //是否允许在主线程查询
           // .allowMainThreadQueries()
           //没有找到Migration就重新创建数据库
            .fallbackToDestructiveMigration()
            .addMigrations(mMigration)
            //数据库创建和打开的回调
            //.addCallback()
            //设置查询的线程池
            //.setQueryExecutor()
            //room的日志模式
            //.setJournalMode()
            //数据库升级异常后根据指定版本进行回滚
            //.fallbackToDestructiveMigrationFrom()
            .build()

    }
    fun providerDB():BackGardenDatabase{
        return backGardenDatabase
    }
}
2.终于可以使用了,哈哈。创建ViewModel类
class MainViewModel : ViewModel() {
    var appModel = AppModel()

    val db by lazy {
        appModel.providerDB()
    }

    fun saveTeacher(teacher: Teacher) {
        db.teacherDao().save(teacher)
    }

    val _teachers = MutableLiveData()

    fun getTeachers():LiveData>{
      return  db.teacherDao().getTeachers()
    }

    fun deleteTeacherById(teacherId: String) {
        db.teacherDao().deleteById(teacherId)
    }

    fun deleteTeacher(teacher: Teacher) {
        db.teacherDao().delete(teacher)
    }

    fun getTeacherById(teacherId: String): Teacher {
     return db.teacherDao().getTeacher(teacherId)
    }
}

在activity中使用viewModel中定义的方法即可

class MainActivity : AppCompatActivity() {
    companion object {
        private const val TAG = "MainActivity"
        private const val TEACHER_PRE_ID = "100"
        private const val STUDENT_PRE_ID = "200"
    }

    val viewModel: MainViewModel by lazy {
        ViewModelProvider(this).get(MainViewModel::class.java)
    }

    val etStudentName: EditText by lazy {
        findViewById(R.id.et_student_name)
    }

    val etTeacherName: EditText by lazy {
        findViewById(R.id.et_teacher_name)
    }
    val etTeacherId: EditText by lazy {
        findViewById(R.id.et_teacher_id)
    }
    val etStudentId: EditText by lazy {
        findViewById(R.id.et_student_id)
    }

    val showContent: TextView by lazy {
        findViewById(R.id.showContent)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        subscribeUI()
    }

    private fun subscribeUI() {
        viewModel.getTeachers().observe(this, { teachers ->
            val stringBuilder = StringBuilder()
            teachers.forEach {
                stringBuilder.append(it.toString()).append("\n")
            }
            showContent.text = stringBuilder
        })
    }


    fun insert(view: View) {
        val teacher: Teacher = generateTeacher()
        viewModel.saveTeacher(teacher)
    }

    private fun generateTeacher(): Teacher {
        val student = generateStudent()
        return Teacher("${TEACHER_PRE_ID}${etTeacherId.text}", etTeacherName.text.toString(), student)
    }

    private fun generateStudent(): Student {
        return Student("${STUDENT_PRE_ID}${etStudentId.text}", etStudentName.text.toString())
    }


    fun delete(view: View) {
        if (TextUtils.isEmpty(etTeacherName.text.toString())) {
            viewModel.deleteTeacherById(etTeacherId.text.toString())
        } else {
            var teacher = viewModel.getTeacherById(etTeacherId.text.toString())
            viewModel.deleteTeacher(teacher)
        }

//        viewModel.deleteTeacher(teacher)
    }

    fun modify(view: View) {
        viewModel.updateTeacher(Teacher(etTeacherId.text.toString(),etTeacherName.text.toString(),null))
    }
    fun query(view: View) {
        var teacher = viewModel.getTeacherById(etTeacherId.text.toString())
        Log.d(TAG, "query: $teacher")
    }
}

你可能感兴趣的:(10分钟学习 Jetpack组件-Room数据库)