当前位置:网站首页>*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

List of articles
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 .

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
边栏推荐
- Some problems of DC-DC bootstrap capacitor
- SISO Decoder for a General (n, N - 1) SPC Code (Supplementary section 3)
- 排序的循环链表
- * Jetpack 笔记 LifeCycle ViewModel 与LiveData的了解
- Use transformers to convert TF model to pytorch model
- [golang] leetcode - 292 Nim games (Mathematics)
- 金融银行_催收系统简介
- Niu Ke brushes the question - no two
- [Golang]力扣Leetcode - 292. Nim 游戏(数学)
- 新项目 搭建环境方法
猜你喜欢

排序的循环链表

SISO Decoder for a General (n, N - 1) SPC Code (Supplementary section 3)

牛客刷题——不要二
![[c language] output the students with the highest scores with a structure. There can be multiple highest scores](/img/4e/836a8f717a2d9bf5f999a934ff4c91.png)
[c language] output the students with the highest scores with a structure. There can be multiple highest scores

H.264概念

Labelme for image data annotation

Monitoring loss functions using visdom

TR-069协议介绍

viso的常见操作

DC-DC自举电容(BOOT)几个问题
随机推荐
Force deduction questions -- create a string based on a binary tree
SISO Decoder for min-sum(补充章节2)
[golang] leetcode - 292 Nim games (Mathematics)
Apipost精妙使用技巧
Quanzhi technology T3 development board (4-core arm cortex-a7) - mqtt communication protocol case
高并发架构设计
Function and principle of key in V-for
MATLAB 保存imshow绘制图片到指定文件夹中的两种方法
New work of "the father of LSTM": a new method towards self correcting neural network
The HashSet collection stores student objects and traverses
力扣刷题——二叉树的最近公共祖先
[c language] output the students within the specified score range with the structure
SISO Decoder for SPC (补充章节1)
Ti am64x - the latest 16nm processing platform, designed for industrial gateways and industrial robots
SISO Decoder for Repetition(补充章节4)
Various poses for text modification using sed
牛客刷题——合法括号序列判断
Force buckle 31 next arrangement
【无标题】
全志科技T3开发板(4核ARM Cortex-A7)——视频开发案例