Android战纪之ObjectBox移动数据库框架探究

ObjectBox移动数据库框架


ObjectBox Github链接:
点击此处链接到Github

  • 介绍
    ObjectBox是移动端数据库框架,灵感来自于NoSql,速度非常快,号称是市面上最快的移动端数据库框架。

  • 为什么要使用

  • 简单,面向对象的API


  • 添加依赖
    项目级别的Gradle中添加:
buildscript {
    ext.objectboxVersion = '1.4.4'
    dependencies {
        classpath "io.objectbox:objectbox-gradle-plugin:$objectboxVersion"
    }
}

module级别的Gradle的头部添加:

apply plugin: 'io.objectbox' // after applying Android plugin

之后Make Project一下项目

  • 新建一个数据库对象,用注解@Entity标注
  • @Id是主键的标识,自增
@Entity
public class UserProfile{
    @Id
    private long id;
    private String name;
    private int age;
    
    public UserProfile(String name, int age){
        this.name = name;
        this.age = age;
    }
}

之后重新编译一下程序,生成MyObjectBox的对象
之后在全局的Application中获取这个对象

public class MyApplication extends Application {

    private BoxStore boxStore;

    @Override
    public void onCreate() {
        super.onCreate();
        boxStore = MyObjectBox.builder().androidContext(this).build();
        if (BuildConfig.DEBUG) {
            new AndroidObjectBrowser(boxStore).start(this);
        }
        
    }

    public BoxStore getBoxStore() {
        return boxStore;
    }
}

之后在相应的Activity或者其他地方调用,每个数据库对象都有自己相应的box

Box<UserProfile> userProfileBox = ((MyApplication)getApplication()).getBoxStore().boxFor(UserProfile.class);

获取到userProfileBox之后,就可以进行相应的增删改查了。


  • UserProfile user1 = new UserProfile("wangming", 18);
    userProfileBox.put(user1);

// 删除id是2的数据
userProfileBox.remove(2);
// 删除所有
userProfileBox.removeAll();
// 调用put方法完成更新
UserProfile user1 = userProfileBox.query().equal(UserProfile_name,"min").build().findFirst();
user1.setName("wangming");
userProfileBox.put(user1);
// 单条件查询:从所有用户中查出name="min"的数据
List<UserProfile> users = userProfileBox.query().equal(UserProfile_.name,"min").build().find();

// 多条件查询:从所有用户中name = "min",age>18,并且secondName是以W开头的
userProfileBox.query().equal(UserProfile_.name,"min")
                    .greater(UserProfile_.age,18)
                    .startWith(UserProfile_.secondName,"W");
                    .build()
                    .find();
                    
//要返回匹配查询的所有实体,只需调用 find()。
//要仅返回第一个结果,请使用 findFirst()。

List item =roleBox.query().startsWith(Role_.role_name,"采")
                        .or().equal(Role_.role_name,"运营")
                        .orderDesc(Role_.created_at).build().find();

QueryBuilder 还提供了greater、less、contain等API
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,932评论 25 709
  • 算命:倒霉或者好运 --- 林海峰作品 2018-03-02 整体自然医学 林海峰作品 人与人,似乎有很大的不同。...
    清远_a429阅读 397评论 0 0
  • 稻盛和夫说现场有神灵。这不是迷信,而是在现场不断的操作、考察,反复的、深入的工作时,用身体去体验、感受,潜意识就容...
    w小郭阅读 289评论 0 0
  • 【这是“心灵·对话”写作小组第五篇文章】 今天我一岁啦~ 一大早就收到了姥爷、爸爸、奶奶的生日祝福,白天妈妈朋友圈...
    富足Linda阅读 403评论 0 0
  • 昨晚没失眠 一觉到天亮 我突然觉得我可以放下他了 实际上并没有 想到他还是不争气的滴眼泪 我还想他 但我知道 我跟...
    今天起床又是一条好汉阅读 195评论 0 0