ObjectBox 怎麼用?

先記錄一下怎麼將ObjectBox 導入到自己的程序中

1、代碼是這個:apply plugin: 'io.objectbox'

2、代碼是這個:

ext.objectboxVersion = '2.3.3'

classpath "io.objectbox:objectbox-gradle-plugin:$objectboxVersion"

需要就是就是這兩步,一共三行代碼。就可以將ObjectBox導入到自己的程序中了。

具體使用

創建需要持久化的類

@Entity//意思是這個User類需要被持久化。

public class User {

@Id public long id;//每一個需要被持久化的類都需要有一個long類型的id(這裏需要說一下的是如果子類和父類都被持久化,那麼只需要在子類中增加這個字段就好)

public String name;

}

附一句官網上面的內容

The best time to initialize ObjectBox is when your app starts. We suggest to do it in the onCreate method of your Application class:

就是說最好的啓動方式 是在app啓動的時候,所以要把ObjectBox的啓動放在自定義的Application中

對Object進行操作時主要分爲以下幾種:

  • put: Inserts a new or updates an existing object with the same ID. When inserting and put returns, an ID will be assigned to the just inserted object (this will be explained below). put also supports putting multiple objects, which is more efficient.

  • get and getAll: Given an object’s ID reads it back from its box. To get all objects in the box use getAll .

  • remove and removeAll: Remove a previously put object from its box (deletes it). remove also supports removing multiple objects, which is more efficient. removeAll removes (deletes) all objects in a box.

  • count: Returns the number of objects stored in this box.

  • query: Starts building a query to return objects from the box that match certain conditions. See queries for details.

2019年12月17日補充用法:

我的用途:項目中的操作比較簡單,就事簡單的增刪改查,其實我覺得手機端也最好是這樣簡單的操作,複雜的操作還是交給服務器來做吧。上面已經將ObjectBox導入到了程序中。下面開始使用。

1.初始化ObjectBox工具類

public class ObjectBox {
    private static BoxStore boxStore;

    public static void init(Context context) {
        boxStore = MyObjectBox.builder().androidContext(context.getApplicationContext()).build();
    }

    public static BoxStore getBoxStore() {
        return boxStore;
    }
}

將這個工具類在MyApplication中初始化

ObjectBox.init(this);

2.設置工具類

把你需要持久化的類中添加一個字段:long類型的id,在輸入上面的@Entity。

3.實現增刪改查

增加的操作比較簡單,直接put就行了

刪除更簡單直接remove就可以了


先查再改。先說查詢吧。

改就直接將查詢的某條數據修改之後,再put一遍就可以了。

這一塊我項目中目前使用的就是簡單的增刪改查。敬請期待下次更新。歡迎留言討論。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章