当前位置:网站首页>*Use of jetpack notes room

*Use of jetpack notes room

2022-06-11 18:32:00 Xia_ A Chinese herb

The other two days I learned LifeCycle ViewModel LiveData as well as DataBinding What I want to learn today is Room

 Insert picture description here

Room Introduction to

Android official ORM library Room
Android use SQLite Store as a database , Common in the open source community ORM(Object Relational Mapping) Library has ORMLite GreenDAO etc. ,Room Like other libraries, it is in SQLite Provide a layer of packaging on .

Room Important concepts
Entity Entity class , This corresponds to a table structure in the database , Using annotations @Entity Mark
Dao Contains access to a series of ways to access the database , Using annotations @Dao Mark
Database Database holder , As the access point for the underlying connection of data related to application persistence . Using annotations
@Database Mark , In addition, the following conditions need to be met The definition class must be a class that inherits from RoomDatabase The abstract class of , In the annotation, you need to define the list of entity classes associated with the database . Contains an abstract method without parameters and returns a Dao object .

 Insert picture description here

Room Use

Here I use Kotlin Code as a case , Finally, add java Code .

Introduce dependency Library

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: "kotlin-kapt"
    implementation "androidx.room:room-runtime:2.2.6"
    kapt "androidx.room:room-compiler:2.2.6"
    implementation "androidx.room:room-ktx:2.2.6"

Room Overview of three parts

Room The group shall consist of three parts :@Entity,@Dao and @Database.
simply ,@Entity Is used to create specific data tables , It is based on data model The form of class , Show the attributes in a data table .
@Dao It's an interface class , Generally, it provides various methods for adding, deleting, modifying and querying a table
@Database As the foundation of the database , Location of database files , The creation of databases is done in this class [email protected] Annotated classes typically provide a singleton object , That is, the database operation object , Then there will be the registration of each data table ( Or a statement ), And the abstract methods for obtaining these data table objects are put into this class [email protected] The annotated class is an abstract class .

establish Entity

Kotlin Created in Entity Follow Java almost , That is to create a data model for Room To use the , There are two ways of writing One is Data How to write it , There is another kind. Class Format , Because of me, I have just finished my studies recently Kotlin Many places are not very skilled , More inclined to Class How to write the format

@Entity(tableName = "student")
class Student() {
    
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
    var name: String = ""
    var age: Int = 0

    constructor(name: String, age: Int) : this() {
    
        this.name = name
        this.age = age
    }

    constructor(id: Int) : this() {
    
        this.id = id
    }

    constructor(id: Int, name: String, age: Int) : this() {
    
        this.id = id
        this.name = name
        this.age = age
    }
}

establish Dao

@Dao
interface StudentDao {
    
    
    @Insert
    fun insertStudent(vararg student: Student)

    @Delete
    fun deleteStudent(vararg students: Student)

    @Update
    fun updateStudent(vararg students: Student)

    @Query("SELECT * FROM student")
    fun getAllStudent(): List<Student>

    @Query("DELETE FROM student")
    fun deleteAllStudents()
    
  //  Used LiveData  Data change direct notification page 
    @Query("SELECT * FROM student")
    fun getAllStudentsLive(): LiveData<List<Student>>

}

establish Database

This is my own way of writing , because Kotlin Not very skilled , It may not be used properly in some places , Follow me later Kotlin Your skills are constantly improving , I'll replace it .

@Database(version = 1, exportSchema = false, entities = [Student::class])
abstract class MyDatabase : RoomDatabase() {
    

    companion object {
    
        private val DATABASE_NAME = "my_db.db"
        @Volatile
        private var mInstance: MyDatabase? = null

        @Synchronized
        fun getInstance(context: Context): MyDatabase {
    
            mInstance?.let {
    
                return it
            }?:let {
    
                mInstance = Room.databaseBuilder(
                    context.applicationContext,
                    MyDatabase::class.java,
                    DATABASE_NAME
                ).fallbackToDestructiveMigration()
                    .build()
                return mInstance as MyDatabase
            }
        }
    }
    
    abstract fun getStudentDao(): StudentDa
}

Repository class ( And Room irrelevant )
Here, for the convenience of operation , Wrote a Repository class , Put it in the sub thread to operate the database , I don't know whether the writing is reasonable , I also hope to meet some big guys to help me take a look .

class StudentRepository(context: Context) {
    

    /** *  Data processing class ,  The operation on the database is a time-consuming operation   I put it in the sub thread for processing  *  Use LiveData  Change data at any time  **/

    var studentDao: StudentDao

    init {
    
        val instance = MyDatabase.getInstance(context)
        studentDao = instance.getStudentDao()
    }

    suspend fun insertStudent(students: Student) = withContext(Dispatchers.IO) {
    
        studentDao.insertStudent(students)
    }

    suspend fun deleteStudent(students: Student) = withContext(Dispatchers.IO) {
    
        studentDao.deleteStudent(students)
    }


    suspend fun deleteAllStudents() = withContext(Dispatchers.IO) {
    
        studentDao.deleteAllStudents()
    }

    suspend fun updateStudent(students: Student) = withContext(Dispatchers.IO) {
    
        studentDao.updateStudent(students)
    }

    fun getAllStudentsLive(): LiveData<List<Student>> {
    
        return studentDao.getAllStudentsLive()
    }

}

viewModel class ( And Room irrelevant )

class StudentViewModel(application: Application) : AndroidViewModel(application) {
    
    var repository: StudentRepository = StudentRepository(application)

    // Enable collaboration processing 
     fun insertStudent(students: Student) {
    
        viewModelScope.launch {
    
            repository.insertStudent(students)
        }
    }

    fun updateStudent(students: Student) {
    
        viewModelScope.launch {
    
            repository.updateStudent(students)
        }
    }

     fun deleteStudent(students: Student) {
    
        viewModelScope.launch {
    
            repository.deleteStudent(students)
        }

    }

     fun deleteAllStudents() {
    
         viewModelScope.launch {
    
             repository.deleteAllStudents()
         }

    }

    fun getAllStudentsLive(): LiveData<List<Student>> {
    
        return repository.getAllStudentsLive()
    }
}

These are the operations of adding, deleting, modifying and querying the database

Room The upgrade

For example, add a new Sex Field

@Entity(tableName = "student")
class Student() {
    
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
    var name: String = ""
    var age: Int = 0
    var sex: Int = 0

    constructor(name: String, age: Int,sex:Int) : this() {
    
        this.name = name
        this.age = age
        this.sex = sex
    }

    constructor(id: Int) : this() {
    
        this.id = id
    }

    constructor(id: Int, name: String, age: Int) : this() {
    
        this.id = id
        this.name = name
        this.age = age
    }
}

stay Database Need to modify

@Database(version = 1, exportSchema = false, entities = [Student::class])
abstract class MyDatabase : RoomDatabase() {
    

    companion object {
    
        private val DATABASE_NAME = "my_db.db"

        @Volatile
        private var mInstance: MyDatabase? = null

        @Synchronized
        fun getInstance(context: Context): MyDatabase {
    
            mInstance?.let {
    
                return it
            } ?: let {
    
                mInstance = Room.databaseBuilder(
                    context.applicationContext,
                    MyDatabase::class.java,
                    DATABASE_NAME
                ).addMigrations(migration1to2)
                    .fallbackToDestructiveMigration()
                    .build()
                return mInstance as MyDatabase
            }
        }
        //  Added version update 
        private val migration1to2: Migration = object : Migration(1, 2) {
    
            override fun migrate(database: SupportSQLiteDatabase) {
    
                database.execSQL("ALTER TABLE student ADD COLUMN 'sex' INTEGER NOT NULL")
            }
        }

    }


    abstract fun getStudentDao(): StudentDao


}

fallbackToDestructiveMigration()
When the update fails
Set up destructive migration , Data and structure are all cleared

原网站

版权声明
本文为[Xia_ A Chinese herb]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111814080067.html