Article Directory
1. Object Relational Mapping- ORM / Object Relational Mapping
The database used in the Android system is a SQLite relational database . It is very cumbersome to use the API provided by Android to access the SQLite database, so many ORM frameworks have emerged;
ORM English full name Object Relational Mapping, Object Relational Mapping;
Object-relational mapping ORM is a programming technology, the mapping between object-oriented programming language and relational database;
- Object refers to object-oriented programming language,
- Relational refers to a relational database;
Using the ORM object-relational mapping framework to access the database can simplify the database operation process . Developers use object-oriented APIs to interact with the database, which is much simpler than writing complex SQL statements to operate the database;
ORM frameworks often use metadata to map database tables with classes in programming languages, and database table fields correspond to fields in classes . The commonly used metadata are:
- annotation
- configuration file
ORM framework advantages:
- Improved development efficiency: using ORM to operate the database simplifies the database operation process and makes the code easier to develop and maintain;
- Improved portability: using the ORM framework to operate the database , the underlying database can be replaced without changing the code;
- Improved performance: The performance of adding, deleting, checking, and modifying operations of the ORM framework can be generally optimized;
- Improved security: SQL injection attacks can be avoided when directly using SQL statements to query;
Common ORM frameworks:
- Android platform: GreenDao / ORMLite ;
- JavaEE Platform: Hibernate ;
- .NET Platform: Entity Framework ;
- Python platform: DiagoORM;
In Android, Google officially provides an ORM framework based on SQLite relational database operation encapsulation, Room framework;
2. The components of the Room framework
1. @Entity / @Dao / @Database annotations
Important annotations in the Room framework:
- @Entity annotation: used to modify the JavaBean entity class, corresponding to a table structure in the database;
- @Dao annotation: used to modify the database access object class, which defines the function of adding, deleting, modifying and checking the database;
- @Database annotation: modify the database holder , the database holder is the database link object, which is the access point of the underlying connection of the application persistent data;
- The class decorated with @Database annotation must inherit the RoomDatabase abstract class;
- In this annotation, a list of database-related entity classes needs to be defined;
- DatabaseHolder contains an abstract method with no parameters that returns a Dao object;
2. The relationship between Entity entity class/Dao database access object/Database database holder
Database database holder, Dao ( Data Access Objects ) database access object, Entity entity class, the relationship between the three is as follows:
- First, in the Android application, get the database holder object through the Database of the Room framework;
- Then, get the Dao (Data Access Objects) database access object through the database holder Database;
- Finally, access the Entity entity class object corresponding to each table in the database through the Dao (Data Access Objects) database access object;
3. Steps to use the Room framework
Room framework usage steps:
- Add Room framework dependency
- Create Entity entity class
- Create Dao entity class
- Create RoomDatabase database instance object
- Initialize the Room database
- Call Dao to perform database addition, deletion, modification and query operations
1. Add Room framework dependency
In the build.gradle build script under the Module module , configure the following dependencies:
dependencies {
// 配置 Room 框架版本号
def room_version = "2.4.0"
// 核心运行时依赖库 在应用运行时提供 Room 框架的数据库相关核心功能
implementation "androidx.room:room-runtime:$room_version"
// 编译时依赖项 在编译时实时生成 Room 代码 如 : Dao 实现类 / AppDatabase 子类 / Entity 实体类映射器
annotationProcessor "androidx.room:room-compiler:$room_version"
// 可选配置项 - 支持 Kotlin 扩展和协程的 Room 框架 如果使用的是 Kotlin 语言必须导入该依赖
implementation "androidx.room:room-ktx:$room_version"
}
The androidx.room:room-runtime dependency library is the runtime core dependency library , which provides the database-related core functions of the Room framework when the application is running; the dependency library contains the core functions of the Room persistence library , such as:
- RoomDatabase class : used to represent the database, which can contain one or more tables, and provides some methods to operate the database, such as inserting, deleting, and querying data.
- Entity annotation : used to mark the entity class, specify the name and field information of the database table corresponding to the entity class, etc.
- Dao database access object : used to define methods to access the database, such as query, insert and delete operations.
- Query annotation : used to mark the method in the DAO interface and specify the SQL query statement.
- PrimaryKey annotation : used to specify the primary key field in the entity class.
- TypeConverters annotation : used to mark type converter classes to convert specific types of data into native types in the database.
The androidx.room:room-compiler dependency library is a compile , which is used to generate the following implementation code of Room at compile time:
- A subclass of AppDatabase for creating and accessing databases;
- Dao database access object implementation class for executing SQL queries and operations;
- The mapper of the entity class Entity is used to map the data in the database to the entity class;
androidx.room: room-ktx depends on the library , which provides Kotlin extension functions. If you use the Kotlin language, you must import the dependent library;
2. Create Entity entity class
Create an Entity entity class, which corresponds to a table in the database , and needs to be modified with the following annotations
- Use the @Entity annotation to modify the entity class and specify the database table name;
- Use the @PrimaryKey annotation to modify the primary key value,
- Use the @ColumnInfo annotation to modify the field corresponding to the column name of the database table;
@Entity(tableName = "users")
data class User(
@PrimaryKey val id: Int,
@ColumnInfo(name = "name") val name: String,
@ColumnInfo(name = "age") val age: Int
)
3. Create Dao entity class
Create Dao entity class: Create a DAO interface for accessing the database, and use annotations to specify information such as SQL query statements;
- Use the @Dao annotation to modify the entire Dao entity class;
- Use the @Query annotation to modify the query function;
- Use the @Insert annotation to modify the insert function;
- Use the @Delete annotation to modify the delete function;
@Dao
interface UserDao {
@Query("SELECT * FROM users")
fun getAll(): List<User>
@Insert
fun insert(user: User)
@Delete
fun delete(user: User)
}
4. Create a RoomDatabase database instance object
Create a RoomDatabase database instance object: create a subclass instance object of RoomDatabase, and define an abstract method to obtain a DAO instance;
@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
5. Initialize the Room database
Initialize the database: before using the Room database in the application, you must first create a database instance;
val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "database-name"
).build()
6. Call Dao to perform database addition, deletion, modification and query operations
Call Dao to perform database addition, deletion, modification and query operations:
db.userDao().insert(User(1, "John", 25))
val users = db.userDao().getAll()