Quickly understand the usage rules of Android Room

2. Add dependencies

1

2

3

dependencies {

    implementation "androidx.room:room-ktx:2.4.0"

}

2、Entity

Entity refers to the class that represents the table in the database, and annotations can be used to define the columns in the table. An Entity class should have at least one primary key field, and can contain other fields, as shown in the following example:

1

2

3

4

5

6

@Entity(tableName = "user")

data class User(

    @PrimaryKey val id: Int,

    @ColumnInfo(name = "name") val name: String,

    @ColumnInfo(name = "email") val email: String

)

3、DAO

DAO refers to the data access object, which is used to define the method of accessing the database. Annotations can be used to specify SQL queries, and some query methods provided by Room can also be used. For example, here's an example DAO with some basic queries:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

@Dao

interface UserDao {

    @Query("SELECT * FROM user")

    fun getAll(): List<User>

    @Query("SELECT * FROM user WHERE id = :id")

    fun getById(id: Int): User?

    @Insert

    fun insert(user: User)

    @Update

    fun update(user: User)

    @Delete

    fun delete(user: User)

}

4、Database

Database refers to a database object that contains configuration information related to the database, such as a version number and a list of entity classes. Annotations can be used to specify database configuration information and included entity classes, as shown in the following example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

@Database(entities = [User::class], version = 1)

abstract class AppDatabase : RoomDatabase() {

    abstract fun userDao(): UserDao

    companion object {

        private var INSTANCE: AppDatabase? = null

        fun getInstance(context: Context): AppDatabase {

            return INSTANCE ?: synchronized(this) {

                val instance = Room.databaseBuilder(

                    context.applicationContext,

                    AppDatabase::class.java,

                    "app_database"

                ).build()

                INSTANCE = instance

                instance

            }

        }

    }

}

5. Get DAO instance

Use the instance method of the Database object to obtain the instance of the DAO interface

1

2

val db = AppDatabase.getInstance(context)

val userDao = db.userDao()

6. Call the DAO method

Use the instance method of the DAO interface to access the database

1

2

3

4

5

6

7

val users = userDao.getAll()

val user = userDao.getById(1)

val newUser = User(2, "鸡你太美", "[email protected]")

userDao.insert(newUser)

newUser.email = "[email protected]"

userDao.update(newUser)

userDao.delete(newUser)

7. Steps to use

The above are the three main components of Room, and the following are some basic steps to use Room:

  • Add dependencies: Add the dependencies of the Room library in the project's build.gradle file.
  • Create Entity classes: Create one or more Entity classes to represent tables in the database.
  • Create a DAO interface: Create one or more DAO interfaces to define methods for accessing the database.
  • Create a Database object: Create an abstract class inherited from RoomDatabase to represent the database object, and use the @Database annotation to specify the configuration information of the database and the included entity classes.
  • Get DAO instance: use the instance method of Database object to get the instance of DAO interface.
  • Call DAO method: use the instance method of DAO interface to access the database.

Let's talk about something else, hehe

8. Transaction

When performing multiple operations on the database, transactions can be used to ensure data consistency and integrity. In Room, you can use the @Transaction annotation to specify that a method is a transaction, for example:

1

2

3

4

5

@Transaction

fun updateUserData(user: User, address: Address) {

    userDao.update(user)

    addressDao.update(address)

}

9. Database Migration

当你需要修改数据库架构时,可以使用Room的数据库迁移功能来升级或降级数据库。在Room中,可以使用@Database注解中的version属性来指定数据库版本号,如果你需要进行迁移,你可以创建一个Migration对象,它包含了旧版本到新版本的变化信息,并将其添加到@Database注解中的migrations属性中,例如:

1

2

3

4

5

6

7

8

@Database(entities = [User::class], version = 2, exportSchema = false,

    migrations = [Migration(1, 2) { database ->

        database.execSQL("ALTER TABLE user ADD COLUMN phone TEXT NOT NULL DEFAULT ''")

    }]

)

abstract class AppDatabase : RoomDatabase() {

    // ...

}

10、视图(View)

在一些情况下,你可能需要使用多个表中的数据来创建一个视图(数据库视图!不是android.view)。在Room中,你可以使用@DatabaseView注解来定义一个视图,并使用@Query注解来指定视图的查询语句,例如:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

@DatabaseView(

    "SELECT user.id, user.name, address.city, address.country FROM user " +

    "INNER JOIN address ON user.address_id = address.id"

)

data class UserAddress(

    val id: Int,

    val name: String,

    val city: String,

    val country: String

)

@Dao

interface UserAddressDao {

    @Query("SELECT * FROM user_address")

    fun getAll(): List<UserAddress>

}

11、Flow!

实际上也支持RXJava,但是我不喜欢RX,可以结合Room、Flow和网络请求,做很酷的事情

1

2

3

4

5

6

7

8

@Dao

interface UserDao {

    @Query("SELECT * FROM user WHERE id = :id")

    fun getById(id: Int): Flow<User>

    @Query("SELECT * FROM user")

    fun getAll(): Flow<List<User>>

}

Guess you like

Origin blog.csdn.net/sinat_40572875/article/details/129303061