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一遍就可以了。

这一块我项目中目前使用的就是简单的增删改查。敬请期待下次更新。欢迎留言讨论。

 

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