Android收藏集Android-JetpackAndroid

Android Jetpack - Room 介绍

2018-12-25  本文已影响270人  Linhaojian
Jetpack.jpg

1.前言


2.简介


3.说明

@Entity
public class User {
    @PrimaryKey(autoGenerate = true)//autoGenerate 为true时,自增;
    private int uid;
    @ColumnInfo(name = "name")
    private String name;
    @Ignore
    private String remark;
    @Embedded
    public Address address;
}
public class Address {
    public String street;
    public String state;
    public String city;
    @ColumnInfo(name = "post_code")
    public int postCode;
}
@Entity(foreignKeys = @ForeignKey(entity = User.class,
                                  parentColumns = "uid",
                                  childColumns = "user_id"))
public class Book {
    @PrimaryKey
    public int bookId;
    public String title;
    @ColumnInfo(name = "user_id")
    public int userId;
}

2.Dao(数据库操作类)

@Dao
public interface UserDao {
    @Query("Select * from user")
    List<User> getAll();
    @Query("Select * from user Where uid In (:userIds)")
    List<User> loadAllByIds(int[] userIds);
    @Insert
    void insertAll(User... users);
    @Delete
    void delete(User... users);
    @Update
    void update(User... users);
    @Query("update user set name =:name1 where uid=:uid")
    void updateCustom(String name1, int uid);
}

3.Database(数据库持久化)

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

4.基本使用

4.1 Lib引用

    // room
    implementation 'android.arch.persistence.room:runtime:1.1.1'
    annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'

4.2 User 实体

@Entity
public class User {
    @PrimaryKey(autoGenerate = true)//autoGenerate 为true时,自增;
    private int uid;
    @ColumnInfo(name = "name")
    private String name;
}

4.3 Dao 操作类

@Dao
public interface UserDao {
    @Query("Select * from user")
    List<User> getAll();
    @Insert
    void insertAll(User... users);
    @Delete
    void delete(User... users);
    @Update
    void update(User... users);
}

4.4 DataBase 数据库持久化

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

4.5 Room初始化

每一次初始化数据库对象都需要消费较大的资源,因此可以通过单例的方式,实现一个进程中公用一个数据库对象。

public class DBInstance {
    private static final String DB_NAME = "room_test";
    public static AppDataBase appDataBase;
    public static AppDataBase getInstance(Context context){
        if(appDataBase==null){
            synchronized (DBInstance.class){
                if(appDataBase==null){
                     return Room.databaseBuilder(context,AppDataBase.class, DB_NAME)
                             .build();
                }
            }
        }
        return appDataBase;
    }
}

4.6 应用

通过DbInstance获取AppDataBase单例 & 操作User数据表

    //获取数据
    List<User> list = DBInstance.getInstance(getApplicationContext()).getUserDao().getAll();
    //插入数据
    User user = new User();
    user.setName("linhaojian");
    DBInstance.getInstance(getApplicationContext()).getUserDao().insertAll(user);
    //更新数据
    user.setUid(1);
    user.setName("linhaojian");
    DBInstance.getInstance(getApplicationContext()).userDao().update(user);
    //删除数据
    DBInstance.getInstance(getApplicationContext()).getUserDao().delete(user);

5.进阶

5.1 版本更新

@Entity
public class User {
    @PrimaryKey(autoGenerate = true)//autoGenerate 为true时,自增;
    private int uid;
    @ColumnInfo(name = "name")
    private String name;
    @ColumnInfo(sex= "sex")
    private String sex;
}

2.修改DateBase的版本信息 1 -> 2

@Database(entities = {User.class},version = 2)
public abstract class AppDataBase extends RoomDatabase {
    public abstract UserDao getUserDao();
}

3.添加一个Migration & 实现版本更新的具体内容

    public static Migration MIGRATION_1_2 = new Migration(1,2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("alter table user add column sex text");
        }
    };

4.在数据库初始化中添加Migration

Room.databaseBuilder(context,AppDataBase.class, DB_NAME)
                             .addMigrations(
                                     VersionDataBase.MIGRATION_1_2)
                             .build()

完成上述4个步骤就可以更新数据库,非常方便,不再像旧式Sqlite需要修改实体类、数据库更新类,还要修改具体的数据表操作的相关方法(增删查改)。

5.2 冲突条款(ON CONFLICT)

conflict-clause.gif
冲突条款 : 就是针对出现约束异常(ROLLBACK, ABORT, FAIL, IGNORE, and REPLACE)的非标准处理。
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    @Update(onConflict = OnConflictStrategy.REPLACE)

6.总结

欢迎关注linhaojian_CSDN博客或者linhaojian_简书

不定期分享关于安卓开发的干货。


写技术文章初心

  • 技术知识积累
  • 技术知识巩固
  • 技术知识分享
  • 技术知识交流
上一篇下一篇

猜你喜欢

热点阅读