ObjectBox使用記錄
學習鏈接: https://blog.csdn.net/vxiaocai/article/details/78711190
引入
1.project的gradle中修改:
buildscript {
repositories {
google()
maven { url 'http://maven.aliyun.com/nexus/content/repositories/google' }
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
maven { url 'http://maven.aliyun.com/nexus/content/repositories/jcenter'}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath "io.objectbox:objectbox-gradle-plugin:2.3.4"
}
}
-
module或者app中引入,需要gradle中最後添加
apply plugin: 'io.objectbox'
3.如果想要查看數據庫。module或者app的gradle中添加
`dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
/*爲了電腦查看數據*/
debugImplementation "io.objectbox:objectbox-android-objectbrowser:2.3.4"
releaseImplementation "io.objectbox:objectbox-android:2.3.4"
}
apply plugin: 'io.objectbox'`
然後application初始化的時候需要打開調試:
`
private BoxStore boxStore;
private void initObjectBox() {
//第一次沒運行之前,MyObjectBox默認會有報錯提示,可以忽略。創建實體類, make之後報錯就會不提示
boxStore = MyObjectBox.builder().androidContext(this).build();
if (BuildConfig.DEBUG) {//開啓瀏覽器訪問ObjectBox
boolean started = new AndroidObjectBrowser(boxStore).start(this);
Log.i("ObjectBrowser", "Started: " + started);
}
DataManager.getInstance().init(this);//數據庫統一操作管理類初始化
}
`
然後可打開鏈接: http://localhost:8090/index.html 查看
備註:如果訪問不到那麼程序安裝後,打開命令行 輸入以下命令 adb forward tcp:8090 tcp:8090
再次嘗試打開鏈接
使用
數據庫使用
- application初始化 BoxStore boxStore = MyObjectBox.builder().androidContext(this).build();
- 添加:boxStore.boxFor(NewUserEntity.class).put(對象實例);
- 查詢:SqlKeyValue sqlKeyValue = beanBox.query().equal(SqlKeyValue_.sqlKey, key).build().findFirst();
- 刪除:beanBox.query().equal(SqlKeyValue_.sqlKey, key).build().remove();
- 更改:先查詢到對象,修改屬性,再添加
數據庫的升級
- 字段的添加或者減少。直接修改對象屬性如添加public String code; 注意屬性爲public或者(provide需要set和get)
- 字段屬性的修改。1.先添加@Uid,運行看報錯如:
error: [ObjectBox] UID operations for property "MyEntity.year": [Rename] apply the current UID using @Uid(6707341922395832766L) - [Change/reset] apply a new UID using @Uid(9204131405652381067L)
在字段前添加@Uid(9204131405652381067L)
3.對象修改:同字段屬性修改
4.數據升級後,保留原數據。
問題記錄
引入不成功
- 檢查project和module中的gradle是否添加
- 定義@Entity對象
- rebuild project
數據升級後,保留原數據
- 添加、刪除 對象字段=數據庫字段;objectbox自動升級數據庫並且保留數據
- 字段的屬性修改需要添加@Uid,以前保存的字段:注意可能爲null