背景
在專案中不可避免的使用資料庫, 而三方框架又是五花八門, 在這中我就選擇了google Jetpack組件中的Room
創建Dao
在room中Dao是一個介面, 通過@Dao注解進行修飾
@Dao
public interface TestDao {
}
添加資料
- 通過
@Insert注解指定方法為添加資料方法, 默認處理模式為忽略當前資料
由于在添加時有可能是一條資料,也有可能是一組資料,所以在這用的是可變陣列
@Insert
void add(TestEntity... entities);
- 更改添加資料模式
剛才說了通過
@Insert注解指定方法默認忽略當前資料, 如果有需求需要替換怎么做呢
通過指定@Insert注解的onConflict來解決 OnConflictStrategy.REPLACE:如果有老的資料存在則會進行替換,如果沒有就插入OnConflictStrategy.ROLLBACK:如果有老的資料存在則會回滾事物,如果沒有就插入OnConflictStrategy.ABORT:如果有老的資料存在則會終止事物,如果沒有就插入OnConflictStrategy.FAIL:如果有老的資料存在則會提示插入資料失敗,如果沒有就插入OnConflictStrategy.IGNORE:如果有老的資料存在則忽略當前資料,如果沒有就插入
用法如下
@Insert(onConflict = OnConflictStrategy.REPLACE)
void add(TestEntity... entities);
洗掉資料
通過@Delete注解指定方法為洗掉資料方法
@Delete
void delete(TestEntity... entities);
更新資料
通過@Update注解指定方法為更新資料方法
@Update
void update(TestEntity... entities);
呼叫邏輯
- 在
AppDatabase中定義Dao對應的方法
public abstract TestDao testDao();
- 定義Dao介面對應的實作類為單例, 并獲取
AppDatabase物件
public class TestRepo {
private static TestRepo sInstance;
private final AppDatabase mDatabase;
private TestRepo(final AppDatabase database) {
mDatabase = database;
}
public static TestRepo getInstance() {
if (sInstance == null) {
synchronized (TestRepo.class) {
if (sInstance == null) {
AppDatabase database = AppDatabase.getInstance();
sInstance = new TestRepo(database);
}
}
}
return sInstance;
}
}
- 封裝方法,并呼叫Dao中對應的增刪改的方法
由于在Dao中add定義的為可變陣列, 所以在Dao實作類中會創建兩個方法, 一個為單條資料, 一個為多條資料, 以便呼叫
以下僅為 添加方法的樣例, 洗掉和修改類似
public void addResults(TestEntity entity) {
mDatabase.testDao().add(entity);
}
public void addResults(List<TestEntity> entities) {
int size = entities.size();
TestEntity[] amHeartRateEntities = new TestEntity[size];
for (int i = 0; i < size; i++) {
amHeartRateEntities[i] = entities.get(i);
}
mDatabase.testDao().add(amHeartRateEntities);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/295213.html
標籤:其他
