Integration and Detailed Explanation of Room Database of Android JetPack Components

background:

one,

The Room database is an official database provided by Google and belongs to the ORM library.

Compared with other ORM frameworks, Room has the following advantages:

  1. Compile-time checking@Query , Room will verify each and so on at compile time @Entity, it not only checks for syntax issues, but also checks for the existence of the table, which means there is almost no risk of any runtime errors
  2. less boilerplate code
  3. Integration with LiveData
     

two,

integrated:

Dependent library:

implementation "android.arch.persistence.room:runtime:1.1.1"
kapt "android.arch.persistence.room:compiler:1.1.1"

The room:compiler library was introduced by annotationProcessor, which may lead to an error: Unable to load class com.google.auto.common.BasicAnnotationProcessor

If you use kapt, if your project supports kotlin, you need to introduce a plug-in that supports kotlin

 

three,

Introduce the room library, we are about to develop the use of the first demo

1. Three major components

1.1: Entity = table library entity object

1.2: Dao:=query module, that is, sql statement, control class of DDL and DML language

1.3Database=database class

 Entity:

We all know that database tables are field-related data. This is easy to understand, a record is the familiarity of an object, so when we create a table, we can mark it with Entity.

as follows:

@Entity(tableName = "user_db")
public class UserEntity {

    /**
     * @Entity The label of the entity class will be mapped to the corresponding table structure in the database. If tableName is not written, it will be the default entity class
     * @PrimaryKey primary key
     * @ColumnInfo If the relationship between the corresponding column of the field attribute does not have this annotation, the attribute name will correspond to the field name one by one
     * @Ignore property values ​​will not be serialized as fields
     */

    @ColumnInfo(name = "age", typeAffinity = ColumnInfo.INTEGER)
    public int age;
    @ColumnInfo(name = "name")
    public String name = "";
    @ColumnInfo(name = "address")
    public String address = "";
    @ColumnInfo(name = "mobile")
    public String mobile = "";
    @PrimaryKey(autoGenerate = true)
    public int id;

}

We created a UserEntity entity and defined some data. Specifies the basic information of the primary key and other columns

If we don’t have ColumnInfo, then the name of the instantiated table is the name of the field. If you want to get familiar with defining new fields in the table, you can do as follows

@ColumnInfo(name = "m_mobile")

public String mobile = "";

If you set the primary key:

@PrimaryKey(autoGenerate = true)

public int id;

The primary key is set. After storage, the primary key is self-incrementing.

Someone may ask what does the typeAffinity attribute mean? We all know that if the format of the input data is not specified, the default is String. If you want to specify the data; type, you can mark it with typeAffinity

Default is: UNDEFINED

@Entity(tableName = "user_db"): Specify the class as a table and specify a table name (tableName).

Normally, the above information can basically meet the normal needs.

Dao:

Dao is the access to data in Java. The same is true here, providing access and operation to the database is a modification of the interface.

@Dao
public interface UserDao {


    @Query("select * from user_db")
    public List<UserEntity> queryAll();

    @Query("select * from user_db where id=:id")
    public UserEntity findUserById(int id);


    @Update()
    public void updateUser(UserEntity entity);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    public long[] inserUser(UserEntity... entities);

    @Delete
    public void deleteUser(UserEntity entity);
}

The basic operations on the data are provided as follows,

1. Query provides a query. Before the Dao class is created, the Entity table should be processed first, because in the Dao operation, if the table is referenced, the tabname of the Entity will be automatically associated.

2. Query: When writing a conditional query, the field connection parameters are as follows

id=:id, the field name in the table=: parameter, not the id=id we wrote.

3. Insert Insert: onConflict conflict resolution mechanism, onConflict = OnConflictStrategy.REPLACE

public @interface OnConflictStrategy {
    /**
     * OnConflict strategy constant to replace the old data and continue the transaction.
     */
    int REPLACE = 1;
    /**
     * OnConflict strategy constant to rollback the transaction.
     */
    int ROLLBACK = 2;
    /**
     * OnConflict strategy constant to abort the transaction.
     */
    int ABORT = 3;
    /**
     * OnConflict strategy constant to fail the transaction.
     */
    int FAIL = 4;
    /**
     * OnConflict strategy constant to ignore the conflict.
     */
    int IGNORE = 5;

}

You can add tags yourself according to your business.

Others can be researched by themselves

3.Database

Database creation: @Database(entities = {UserEntity.class}, version = 1)

Entities is a table in parentheses, which is the mark we inject with entity. The last parameter is the version number.

Here, a piece of data has at least one table, and there can be multiple tables in brackets. This table must integrate RoomDatabase, which is an abstract class, as follows:

@Database(entities = {UserEntity.class}, version = 1)
public abstract class MyRoomDataBase extends RoomDatabase {
    public abstract UserDao getUserDao();

}

We created our own database with a table in it, and created an abstract Dao in this database to operate on the data.

The above three cores have been introduced. Next, we need to do a core operation, which is to build the project. If the project is successfully executed, a new Impl class will be generated for the Database and Dao classes, as follows:

The MyRoomDataBase_Impl class is as follows:

Dynamic creation of data and generation of dao. The specific code can be created by yourself and then viewed

 
 

The UserDao_Impl class is as follows:

Automatically generate some database operation classes and we define DDL operation methods, these are the automatic generation of sql statements

If these two classes are generated, our database is basically complete. If it is not generated, it is only useful to explain what we referenced. Even if you operate these databases, you will not be able to execute successfully.

Four,

Data references:

Connect to the database:

MyRoomDataBase   dataBase = Room.databaseBuilder(this, MyRoomDataBase.class, "userDataBase").build();

  parameter, 

  Context: passed in directly

Class<T> klass: It is a class modified by the database class @Databasex
name: database name

The database can only be operated after the creation is successful

Dao operation data needs to be completed in sub-threads, because Dao is time-consuming, and if it is directly operated on the UI thread, an error will be reported .

UserEntity entity = new UserEntity();
entity.address = "Jiangsu Nanjing";
entity.age = 12;
entity.mobile = "110";
entity.name = "Zhang Silly";

if (dataBase == null) {
    showToast("Database initialization failed");
    return;
}
new Thread(new Runnable() {
    @Override
    public void run() {
        dataBase.getUserDao().inserUser(entity);
    }
}).start();

2. The operation of the database itself can be operated through dataBase,

Open: Once created, it is opened

关:dataBase.close()

Whether to open: dataBase.isOpen()

Database name: dataBase.getOpenHelper().getDatabaseName()

Database version number: dataBase.getOpenHelper().getReadableDatabase().getVersion()

Configure your own things: dataBase.beginTransaction();dataBase.endTransaction();

Operations on the database: can be managed by creating a database.

The above basically completes the basic operation of the room database

Guess you like

Origin blog.csdn.net/qq36246172/article/details/126385379