Room persistent library
Room provides an abstraction layer on top of SQLite that takes full advantage of SQLite’s capabilities while allowing for more powerful database access.
This library helps you create a cache of app data that acts as the app’s only real data source, allowing users to view a consistent copy of key information in the app regardless of whether there is a network connection.
Use Room to save data to a local database
Room provides an abstraction layer on top of SQLite, allowing smooth database access while taking full advantage of SQLite’s power
Storing data locally is useful for apps that need to process large amounts of structured data. The most common use case is caching related data so that users can still browse the cached data when the device is disconnected from the Internet, and any changes made by the user are synchronized to the server when the device is reconnected.
Because Room helps you solve these problems, we strongly recommend Using Room instead of SQLite. If you prefer to use SQLite APIs directly, read Save Data Using SQLite
There are three main components in Room
- Database: Contains the holder of the Database and serves as the primary access point for the underlying persistent relational Database connection. be
@Database
Annotated classes should meet the following criteria:- inheritance
RoomDatabase
The abstract class - Include a list of entities associated with the database in the annotation
- Contains an abstract method with no arguments that returns by
@Dao
Annotated classes at run time that you can passRoom.databaseBuilder() or Room.inMemoryDatabaseBuilder().
Access to theDatabase
An instance of the
- inheritance
- Entity: indicates a table in the Entity database
- DAO: Contains methods to access the database
App obtains the data access object (DAO) associated with it from the Room database. App then obtains Entities from the database through the DAO and writes all changes to Entities back to the database. As a result, the Entity used by the app corresponds to the columns in the data table.
The relationship between different components of Room is shown in the following figure
The following code snippet contains a basic database configuration and an Entity, a data access object DAO
User
@Entity
data class User(
@PrimaryKey val uid: Int,
@ColumnInfo(name = "first_name") val firstName: String? , @ColumnInfo(name ="last_name") val lastName: String?
)
Copy the code
UserDao
@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>
@Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
"last_name LIKE :last LIMIT 1")
fun findByName(first: String, last: String): User
@Insert
fun insertAll(vararg users: User)
@Delete
fun delete(user: User)
}
Copy the code
AppDatabase
@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
Copy the code
After creating the above file, you get the database entity with the following code.
val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "database-name"
).build()
Copy the code
Note: If your app is running in a single-process environment, it is recommended to use singleton mode to initialize AppDatabase objects. Each RoomDatabase instance is expensive to create, and you rarely need to use multiple instances of it in a single process
If your app is running in multiple processes, remember in the database builder plus enableMultiInstanceInvalidation (), so that when you are in a process will be a Shared database file is marked as invalid, This behavior is automatically passed to the database of other processes
0. Overview
1. Use Room entities to define data
2. Define relationships between objects
3. Create a view in the database
4. Use Room DAOs to access data
5. Migrate the database
6. Test the database
7. Reference complex data using Room