Use of 0.37 root data store for android development process

Keywords: Android

Introduction to room data storage

room is a data persistence Library in the jetpack library, and the underlying implementation is using SQLite. However, the way to use it is simpler, the native SQLite method is more cumbersome, and root uses the way that entity classes and database tables are mapped. More concise and understandable. *

room Database Import

Add in the module's gradle:

    def room_version = "2.3.0" // check latest version from docs
    implementation "androidx.room:room-ktx:$room_version"
    kapt "androidx.room:room-compiler:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

Note that kapt must be added after the project uses kotlin, and that it is not database-related code that needs to be imported using kotlin. As long as the project imports kotlin, you need to import kotlin's libraries. There are other class libraries on GitHub that may be used, such as rxjava.

Use of root database

Setting up data tables

The mapping of a room database set to entity classes and tables starts with how to create a basic data table:

@Entity(tableName = "User")
public class User {
    @PrimaryKey((autoGenerate = true))
    @ColumnInfo(name = "id")
    private int id;
    @ColumnInfo(name = "name")
    private String name;
    @ColumnInfo(name = "password")
    private String password;
}

In the code above, we omitted constructors and methods to get class variables. You can see that root uses annotations to simplify the operation, @Entity annotations indicate that this class is a database table, and tableName sets the table name, which is the class name if the processing table name is not displayed. Variable comment @Primarykey sets the primary key and whether it increases by itself, @ColumnInfo is required and sets the variable to the column name of the database.

Set up database

The code for setting up the database is as follows: UserDataDao is the database method we are going to encapsulate.

@Database(entities = {User.class}, version = 1)
public abstract class UserDataBase extends RoomDatabase {
    private static UserDataBase instance;
    public static UserDataBase getInstance(Context context) {
        if (instance == null) {
            instance = Room.databaseBuilder(context.getApplicationContext(), UserDataBase.class,"userdatabase")
                    .allowMainThreadQueries()
                    .addMigrations(MISGRATION_1_2)
                    .fallbackToDestructiveMigration()
                    .build();
        }
        return instance;
    }
    public abstract UserDataDao userDataDao();

The entities in note @Database associate database tables with databases, followed by versions indicating the version of the database, which is used in database updates. Create a database using a static method, the allowMainThreadQueries method setting reads the database in the main thread, addMigrations adds a database upgrade policy, and fallbackToDestructiveMigration s allows rebuilding after a database upgrade fails rather than crashing directly.

Database Access Dao

@Dao
public interface UserDataDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insert(User...users);
    @Update
    void updata(User...users);
    @Delete
    void delete(User...users);
    @Query("Select * from User")
    List<User> selectAll();
}

With the annotations already set, OnConflictStrategy sets the conflict resolution policy, which overrides a row when it is inserted if it already exists. room automatically generates an impl class that implements the specific SQL execution process.

Usage

    userDataBase = UserDataBase.getInstance(this);
    userDataDao=userDataBase.userDataDao();
    User user=new User(1, "11", "111");
    userDataDao.insert(user);
    List<User> userList= userDataDao.selectAll();
    tvMain.setText(userList.toString());

Upgrade of root database

Database upgrade is dangerous and can easily cause crashes. Client database upgrade scenarios are different from server database upgrade scenarios. Imagine a scenario where an app upgrade version increases the number of fields in the database tables in the new version, and you don't want to discard the data you saved locally. Note version changes and different migration strategies, such as 1 migrating to 22 migrating to 3. Current versions such as 3 may also need to add 1 to 3 methods to prevent errors. Here are a few migration examples:

    static Migration MISGRATION_1_2=new Migration(1,2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //Migrate Example 1 to create a new table
              database.execSQL("CREATE TABLE `Fruit` (`id` INTEGER, "
                + "`name` TEXT, PRIMARY KEY(`id`))");
                   database.execSQL("ALTER TABLE Book "
                + " ADD COLUMN pub_year INTEGER");

            //Migration Example 2 Add Field
                 database.execSQL("ALTER TABLE Book "
                + " ADD COLUMN pub_year INTEGER");

            //Migration Example 3 Traverses Modified Fields
            Cursor cursor= database.query("select * from User");
            do {
                while (cursor.moveToNext()) {
                    Log.e("TAG", "migrate: "+cursor.getString(cursor.getColumnIndex("password")) );
                    String sql="insert into User (password) values (?)";
                    SupportSQLiteStatement statement= database.compileStatement(sql);
                    statement.bindString(1, "22222");
                    statement.execute();
                }
            }while (cursor.moveToFirst());
        }
    };

Other

android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation":
                             "$projectDir/schemas".toString()]
            }
        }
    }
}

gradle This setting allows you to export database-related information, including table-building statements, query statements, and so on.

Posted by aayatoos on Wed, 03 Nov 2021 10:15:01 -0700