今天看新闻,发现 GreenDao 的东家 greenrobot 出了一个新的 NoSQL 数据库,greenrobot 称它是目前性能最好且易用的 NoSQL 数据库,且优于其它数据库 5~15 倍的性能。
首先为什么我们需要这个数据库, greenrobot 介绍了它的5个特性:
首先要如下修改 gradle 来添加依赖:
buildscript {
repositories {
jcenter()
mavenCentral()
maven {
url "http://objectbox.net/beta-repo/"
}
}
dependencies {
classpath 'io.objectbox:objectbox-gradle-plugin:0.9.6'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.objectbox'
repositories {
jcenter()
mavenCentral()
maven {
url "http://objectbox.net/beta-repo/"
}
}
dependencies {
compile 'io.objectbox:objectbox-android:0.9.6'
}
在 Application 中初始化:
// 在 Application 中初始化 boxStore = MyObjectBox.builder().androidContext(App.this).build();
Entity 是需要被持久化保存的类。我们需要用 @Entity
注解来标注它,属性通常 private
修饰,然后会自动生成 getter
、 setter
。
在 ObjectBox 中,每一个 Entity 都需要有 long
类型的 ID 属性,我们需要使用 @Id
来标注它。
@Entity
public classUser{
@Id
private long id;
...
}
ID 有以下需要注意的点:
@Id(assignable = true)
,这样就不会检查插入对象时对象的 Id 通常我们不需要在属性上使用注解,除非:
@Property
注解 @Transient
注解 @Entity
public classUser{
@Property(nameInDb = "USERNAME")
private String name;
@Transient
private int tempUsageCount;
...
}
使用 @Index
注解可以生成索引,加快查询速度。
@Entity
public classUser{
@Id
private Long id;
@Index
private String name;
}
使用 @Relation
注解可以标注关联关系。
customId 属性会自动生成。
@Entity
public classOrder{
@Id long id;
long customerId;
@Relation
Customer customer;
}
@Entity
public classCustomer{
@Id long id;
}
一对多的时候,只能修饰 List。
@Entity
public classCustomer{
@Id long id;
// References the ID property in the *Order* entity
@Relation(idProperty = "customerId")
List<Order> orders;
}
@Entity
public classOrder{
@Id long id;
long customerId;
@Relation Customer customer;
}
首先要获取 Box 对象,然后通过 QueryBuilder 查询,以下是一个找出 firstName 是 Joe 的例子:
Box<User> userBox = boxStore.boxFor(User.class); List<User> joes = userBox.query().equal(User_.firstName, "Joe").build().find();
QueryBuilder 还提供了形如 greater
、 startsWith
等 API,使用非常方便。
Query<User> query = userBox.query().equal(UserProperties.FirstName, "Joe").build(); List<User> joes = query.find(10 /** offset by 10 */, 5 /** limit to 5 results */);
offset
: 查询的第一项的 offset limit
: 查询多少项 查询的结果可以直接修改和删除,会同步数据库更改结果。
Box 对象的 put
方法可以插入对象,通常主键的值是 0,如果服务器已经确定主键了需要添加注解标注。
笔者简单测试了一下和 Realm 对比的性能差距,以 2000 个简单对象为例:
生成 2000 个对象一次性插入数据库
查询所有 2000 条数据
删除所有 2000 条数据
可以看出 ObjectBox 性能确实比 Realm 优秀。
更复杂的性能对比后期再测试。