Jetpack series [x] - Room to operate the database

Room Jetpack assembly operation of the database

Read google produced jetpack library, the feeling is still very good, here on our journey of learning Jetpack

All source code included in this article -> https://github.com/ddssingsong/AnyTool

Brief introduction

official:

Room persistence library provides an abstraction layer on sqlite, at the same time in order to take full advantage of the power of the sqlite, more reliable access to the database.

The library helps you create a cache application data on the device running the application. This cache is the only real source of the application, allowing users to view a copy of the same application critical information, regardless of whether the user has an Internet connection.

Nature:

In fact, an ORM library, which spent a lot of notes, and can also be used in conjunction with other components jetpack.

The main class

  1. @Database: @Database used to annotate classes and annotated class must be inherited from RoomDatabase abstract class. This class main role is to create the database and create Daos (data access objects, data access objects).
  2. @Entity: @Entity used to annotate entity classes, @ Database references are annotated classes by entities @Entity property, and using all the fields of the class as the column names in the table to create the table.
  3. @Dao: @Dao annotation to an interface or abstract methods, such effect is to provide a method to access the database. Annotations using @Database a given class have a method without parameters, the method returns annotated classes @Dao

rely

implementation 'android.arch.persistence.room:runtime:1.1.1'
annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'
// test
androidTestImplementation "android.arch.persistence.room:testing:1.1.1"

Defined entity classes

@Entity annotation using the entity class, as defined herein, and two classes UserInfo MessageBean

  1. @PrimaryKey: defining at least one primary key field as
  2. If the self-growth ID autoGenerate use of property set @PrimaryKey
  3. @Entity combination of the primary key attribute @primaryKeys
  4. Room is used by default as the field name to the column name to be modified to use @ColumnInfo (name = "***")
  5. @Entity using indices of property to add indexes
  6. Foreign key constraint @ForeignKey

UserInfo


// @Entity(primaryKeys = {"userId", "userName"})  // 组合主键
// @Entity(indices = {@Index(name = "userName", value = {"name"}), @Index(name = "email", value = {"email"})})                              // 创建索引

@Entity(tableName = "user_info")
public class UserInfo {
    @PrimaryKey
    @ColumnInfo(name = "userId")
    private long userId;
    @ColumnInfo(name = "userName")
    private String userName;
    @ColumnInfo(name = "nickName")
    private String nickName;
    @ColumnInfo(name = "avatar")
    private String avatar;
    @ColumnInfo(name = "email")
    private String email;
 }
    

MessageBean

// 外键的写法
//@Entity(foreignKeys = {
//        @ForeignKey(entity = UserInfo.class, parentColumns = {"userId"}, childColumns = //        {"userId"}),
//        @ForeignKey(entity = UserInfo.class, parentColumns = {"userId"}, childColumns = //        {"fromId"})})
  
@Entity(tableName = "message")
public class MessageBean {
    @ColumnInfo(name = "msgId")
    private long msgId;
    @ColumnInfo(name = "userId")
    private long userId;
    @ColumnInfo(name = "fromId")
    private long fromId;
    @ColumnInfo(name = "content")
    private String content;
    @ColumnInfo(name = "mediaFilePath")
    private String mediaFilePath;
    @ColumnInfo(name = "updateTime")
    private long updateTime;
    @ColumnInfo(name = "msgType")
    private int msgType;

Access to data

Dao core data definitions, mainly for database CRUD

@Dao
public interface UserDao {

    @Query("Select * from user_info")
    List<UserInfo> getAll();

    @Insert
    void insert(UserInfo users);

    @Delete
    void delete(UserInfo users);

    @Update
    void update(UserInfo users);
}

Create a database

@Database annotations mainly used in the data holder classes, where class needs to meet certain conditions annotation

  1. You must inherit RoomDatabase
  2. The method comprises at least an abstract class annotated with @Dao
  3. Entities included in the entity list parameters associated database
  4. Examples of initialization takes a long time, it is necessary to initialize a single embodiment example
@Database(entities = {UserInfo.class, MessageBean.class}, version = 1)
public abstract class AppDataBase extends RoomDatabase {
    // 用户信息操作类
    public abstract UserDao getUserDao();
    // 消息列表操作类
    public abstract MessageDao getMessageDao();
}

Embodiment provides a method using a single outwardly

  private static final String DB_NAME = "room_db";
    // 静态内部类
    private static class Holder {
        private volatile static AppDataBase appDataBase = null;

        static AppDataBase getInstance(Context context) {
            if (appDataBase == null) {
                synchronized (AppDataBase.class) {
                    if (appDataBase == null) {
                        appDataBase = buildDatabase(context);
                    }
                }
            }
            return appDataBase;
        }

        private static AppDataBase buildDatabase(Context context) {
            return Room.databaseBuilder(context, AppDataBase.class, DB_NAME)
                    .addCallback(new RoomDatabase.Callback() {
                        @Override
                        public void onCreate(@NonNull SupportSQLiteDatabase db) {
                            super.onCreate(db);
                            // 第一次创建数据库会回调此方法,可以做初始化数据之类的操作
                            Log.e(DB_NAME, "room_db 数据库第一次创建成功!");
                            
                        }

                        @Override
                        public void onOpen(@NonNull SupportSQLiteDatabase db) {
                            super.onOpen(db);
                            Log.e(DB_NAME, "room_db 数据库 onOpen!");
                        }
                    })
                    .build();
        }
    }
    // 向外提供方法
    public static AppDataBase getAppDataBase(Context context) {
        return Holder.getInstance(context);
    }

Insert data

  UserInfo userInfo = new UserInfo();
    userInfo.setUserId(new Random().nextInt(10000));
    userInfo.setUserName("大大帅");
    userInfo.setNickName("屠~~");
    userInfo.setAvatar("jpeg");
    userInfo.setEmail("[email protected]");
                AppDataBase.getAppDataBase(RoomActivity.this).getUserDao().insert(userInfo);

delete data

UserInfo userInfo = new UserInfo();
userInfo.setUserId(4934); // 主键
AppDataBase.getAppDataBase(RoomActivity.this).getUserDao().delete(userInfo);

update data

UserInfo userInfo = AppDataBase.getAppDataBase(RoomActivity.this).getUserDao().getUser();
userInfo.setUserName("小小帥");
                AppDataBase.getAppDataBase(RoomActivity.this).getUserDao().update(userInfo);

To be continued ...

Tips

All of the code included in this article: https://github.com/ddssingsong/AnyTool

Guess you like

Origin blog.csdn.net/u011077027/article/details/92655922