1. Preface
Recently, in development, Room is used more often. I have to check information from time to time, so I simply write an article on the use of Room and the packaging of Room. If you write it badly or have any errors, please point it out in your comments, private messages, or email address. Thank you very much 🙏
2. Add dependencies
dependencies { implementation ":room-ktx:2.4.0" }
2、Entity
Entity refers to a class that represents a table in a database, and columns in a table can be defined using annotations. An Entity class should have at least one primary key field and can contain other fields, as shown in the following example:
@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 a data access object, used to define a method to access a database. You can use annotations to specify SQL queries, or you can use some query methods provided by Room. For example, here is an example of a DAO with some basic queries:
@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 list of version numbers and entity classes. Annotations can be used to specify the configuration information of the database and the entity classes it contains, as shown in the following example:
@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 = ( , AppDatabase::, "app_database" ).build() INSTANCE = instance instance } } } }
5. Obtain DAO instance
Use the instance method of the Database object to get an instance of the DAO interface
val db = (context) val userDao = ()
6. Call the DAO method
Use instance methods of DAO interface to access the database
val users = () val user = (1) val newUser = User(2, "You're so beautiful", "jinitaimei@") (newUser) = "jinitaimei@" (newUser) (newUser)
7. Steps to use
The above are the three main components of Room. Here are some basic steps to using Room:
- Add dependencies: Add dependencies of the Room library in the project's file.
- Create Entity class: Create one or more Entity classes to represent tables in the database.
- Create DAO interface: Create one or more DAO interfaces to define methods to access the database.
- Create Database object: Create an abstract class inherited from RoomDatabase to represent the database object, and use @Database annotation to specify the configuration information of the database and the entity class contained.
- Get DAO instance: Use the instance method of the Database object to obtain an instance of the DAO interface.
- Calling DAO method: Use instance methods of the DAO interface to access the database.
Let's talk about other things, hehe
8. Transaction
When performing multiple operations on the database, transactions can be used to ensure the consistency and integrity of the data. In Room, you can use the @Transaction annotation to specify that a method is a transaction, for example:
@Transaction fun updateUserData(user: User, address: Address) { (user) (address) }
9. Database migration
When you need to modify the database schema, you can use Room's database migration feature to upgrade or downgrade the database. In Room, you can use the version attribute in the @Database annotation to specify the database version number. If you need to migrate, you can create a Migration object that contains the changes from the old version to the new version and add it to the migrations attribute in the @Database annotation, for example:
@Database(entities = [User::class], version = 2, exportSchema = false, migrations = [Migration(1, 2) { database -> ("ALTER TABLE user ADD COLUMN phone TEXT NOT NULL DEFAULT ''") }] ) abstract class AppDatabase : RoomDatabase() { // ... }
10. View
In some cases, you may need to use data from multiple tables to create a view (database view! not). In Room, you can use the @DatabaseView annotation to define a view and use the @Query annotation to specify the view's query statement, for example:
@DatabaseView( "SELECT , , , FROM user " + "INNER JOIN address ON user.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!
Actually, RXJava is also supported, but I don't like RX. I can do cool things with Room, Flow and network requests.
@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>> }
Ending
In fact, Room applications are much more than that. If anyone is interested, I will release the next issue! For example, encapsulating a room's database layer
grateful
- Proofreading: ChatGpt/Bing
- Writing Optimization: ChatGpt/Bing/My Tower Writing Cat
The above is a detailed content of the Android Room usage details. For more information about Android Room usage, please follow my other related articles!