Detailed explanation of the use of Android Room

Detailed explanation of the use of Android Room

1: Basic introduction to Room

 Room 是 Android 架构组件的一部分,Room 持久性库在 SQLite
 上提供了一个抽象层,以便在充分利用 SQLite 的强大功能的
 同时,能够流畅地访问数据库。具体来说,Room 具有以下优势:
  • Compile-time validation for SQL queries.
  • Handy annotations that minimize repetitive and error-prone boilerplate code.
  • Simplified database migration path

Two: The Room library consists of 3 main components:

entity:

Entity represents a table in the database and must be annotated with @Entity. Every entity contains at least one field and must define a primary key.

DAO (Database Access Object):

In Room, you can use data access objects to access and manage your data. The DAO is the main component of Room and includes methods that provide access to your application's database, which must be annotated with @Dao. Using a DAO instead of a query builder lets you separate the different components of the database, such as current data and statistics, which allows you to easily test the database.

database:

As the database holder, it is the main access point for relational data. It must be annotated with @Database and extend RoomDatabase. It also contains and returns a Dao (Database Access Object).

​​insert image description here

Three: Implement Room database in Android application

​​​​​​Step 1: Create an Empty Activity project

    创建一个空的活动项目,并选择Kotlin作为语言。

Step Two: Add Required Dependencies

    将以下依赖添加到应用级gradle 文件中。通过转到

    ProjectName -> src -> build.gradle.
dependencies {
    
    
    val room_version = "2.4.3"

    implementation("androidx.room:room-runtime:$room_version")
    annotationProcessor("androidx.room:room-compiler:$room_version")

    // To use Kotlin annotation processing tool (kapt)
    kapt("androidx.room:room-compiler:$room_version")
    // To use Kotlin Symbol Processing (KSP)
    ksp("androidx.room:room-compiler:$room_version")

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation("androidx.room:room-ktx:$room_version")

    // optional - RxJava2 support for Room
    implementation("androidx.room:room-rxjava2:$room_version")

    // optional - RxJava3 support for Room
    implementation("androidx.room:room-rxjava3:$room_version")

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation("androidx.room:room-guava:$room_version")

    // optional - Test helpers
    testImplementation("androidx.room:room-testing:$room_version")

    // optional - Paging 3 Integration
    implementation("androidx.room:room-paging:2.5.0-beta02")
}

​Step 3

    创建一个名为 User.kt的示例数据类。

    并调用以下代码,其中包含实体User作为实体,它表示行,first_ name、last_name、 age 表示表的列名。

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
 
@Entity
data class User(
	@PrimaryKey(autoGenerate = true) val uid: Int,
	@ColumnInfo(name = "name") val firstName: String?,
	@ColumnInfo(name = "city") val lastName: String?
)

Step 4: Create a data access object (DA0):

    现在创建一个名为UserDao.kt的接口。

    并调用以下代码,它提供了应用程序用来与用户交互的各种方法。

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
 
@Dao
interface UserDao {
    
    
	@Query("SELECT * FROM user")
	fun getAll(): List<User>
 
	@Query("SELECT * FROM user WHERE uid IN (:userIds)")
	fun loadAllByIds(userIds: IntArray): List<User>
 
	@Insert
	fun insertAll(vararg users: User)
 
	@Delete
	fun delete(user: User)
}


Step 5:​​​​​​​​Create a database

    现在创建定义实际应用程序数据库的数据库,它是应用程序持久数据的主要访问点。这个类必须满足:

    1、类必须是抽象的。

    2、该类应该用@Database注释。

    3、数据库类必须定义一个带有零参数的抽象方法并返回一个 DAO 实例。

    现在在AppDatabase.kt文件中调用以下代码。
import androidx.room.Database
import androidx.room.RoomDatabase
  
@Database(entities = arrayOf(User::class), version = 1)
abstract class UserDatabase : RoomDatabase() {
    
    
    abstract fun userDao(): UserDao
}

Step 6: Use of the Room database

在MainActivity.kt文件中,我们可以通过为数据库提供自定义名称来创建数据库
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.room.Room
 
class MainActivity : AppCompatActivity() {
    
    
 
	// application's Database name
	private val DATABASE_NAME: String = "USER_DATABASE"
 
	override fun onCreate(savedInstanceState: Bundle?) {
    
    
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_main)
 
		// get the instance of the application's database
		val db = Room.databaseBuilder(
			applicationContext, UserDatabase::class.java, DATABASE_NAME
		).build()
 
		// create instance of DAO to access the entities
		val userDao = db.userDao()
 
		// using the same DAO perform the Database operations
		val users: List<User> = userDao.getAll()
	}
}


Author: Lin Jiangpeng
Original link: https://blog.csdn.net/m0_52768965/article/details/128064067?spm=1001.2014.3001.5501

Guess you like

Origin blog.csdn.net/fjnu_se/article/details/128173203