2. Add dependencies
1 2 3 |
|
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 |
|
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 |
|
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 |
|
5. Get DAO instance
Use the instance method of the Database object to obtain the instance of the DAO interface
1 2 |
|
6. Call the DAO method
Use the instance method of the DAO interface to access the database
1 2 3 4 5 6 7 |
|
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 |
|
9. Database Migration
当你需要修改数据库架构时,可以使用Room的数据库迁移功能来升级或降级数据库。在Room中,可以使用@Database注解中的version属性来指定数据库版本号,如果你需要进行迁移,你可以创建一个Migration对象,它包含了旧版本到新版本的变化信息,并将其添加到@Database注解中的migrations属性中,例如:
1 2 3 4 5 6 7 8 |
|
10、视图(View)
在一些情况下,你可能需要使用多个表中的数据来创建一个视图(数据库视图!不是android.view)。在Room中,你可以使用@DatabaseView注解来定义一个视图,并使用@Query注解来指定视图的查询语句,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
11、Flow!
实际上也支持RXJava,但是我不喜欢RX,可以结合Room、Flow和网络请求,做很酷的事情
1 2 3 4 5 6 7 8 |
|