写入数据库
- 写操作必须在 transactions 中执行。
- 在写的时候同时可以读
- 方式一:
realm.beginTransaction();
User user = realm.createObject(User.class); // Create a new object
user.setName("John");
user.setEmail("john@corporation.com");
realm.commitTransaction();
User user = new User("John");
user.setEmail("john@corporation.com");
// Copy the object to Realm. Any further changes must happen on realmUser
realm.beginTransaction();
User realmUser = realm.copyToRealm(user);
realm.commitTransaction();
List<User> users = Arrays.asList(new User("John"), new User("Jane"));
realm.beginTransaction();
realm.insert(users);
realm.commitTransaction();
- 使用insert() 或者 insertOrUpdate() 不用返回对象 所以插入更快 当有很多对象要插入的时候可以使用
更新数据
- 在realm数据库中不能直接更新单个string或者bytes数据 只能 读出来 并且再写回去 TODO (确定这里的类型修改)
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
bytes[] bytes = realmObject.binary;
bytes[4] = 'a';
realmObject.binary = bytes;
}
});
查询数据
// Build the query looking at all users:
RealmQuery<User> query = realm.where(User.class);
// Add query conditions:
query.equalTo("name", "John");
query.or().equalTo("name", "Peter");
// Execute the query:
RealmResults<User> result1 = query.findAll();
// Or alternatively do the same all at once (the "Fluent interface"): 可以简写成以下的形式
RealmResults<User> result2 = realm.where(User.class)
.equalTo("name", "John")
.or()
.equalTo("name", "Peter")
.findAll();
- RealmQuery 对象提供四个方法 :findAll findAllAsync findFirst findFirstAsync
- RealmResults is a list 。 可以通过下标的形式访问每一个对象。如果查询结果没有的话。那么 RealmResults的size为0;
查询的过滤条件
- 所有数据类型都可以使用
- equalTo
- notEqualTo
- in For example, to find the names “Jill,” “William,” or “Trillian”, you can use in("name", new String[]{"Jill", "William", "Trillian"}).
- 数字类型的数据
- between (includes both end points, i.e., it is a bounded interval)
- greaterThan
- lessThan
- greaterThanOrEqualTo
- lessThanOrEqualTo
- string类型的数据
- contains
- beginsWith
- endsWith
- like
TODO 查询的东西没有看完 再看吧 不是现在
Transaction
executeTransaction()
- 这个方法自动执行beginTransaction, commitTransaction, and cancelTransaction (当Transaction有一场的时候 自动执行cancel)
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
User user = realm.createObject(User.class);
user.setName("John");
user.setEmail("john@corporation.com");
}
});
异步Transaction
- 当一个Transaction 执行的时候,另外一个会被锁住。所以需要异步。 success和error方法是可以设置为null的。
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm bgRealm) {
User user = bgRealm.createObject(User.class);
user.setName("John");
user.setEmail("john@corporation.com");
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
// Transaction was a success.
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
}
});
public void onStop () {
if (transaction != null && !transaction.isCancelled()) {
transaction.cancel();
}
}
网友评论