标签:
Realm是一个轻量级的数据库,在Android开发中,它可以替代 SQLite 和 ORM 框架。相比SQLite,Realm更快并且具有很多现代数据库的特性,比如支持JSON,流式api,数据变更通知,以及加密支持。
官网主页:realm官网
GutHub地址:realm的GitHub地址
1、在工程根目录的build.gradle中添加dependencies
classpath "io.realm:realm-gradle-plugin:1.1.0"2、在app的build.gradle中添加plugin
apply plugin: ‘realm-android‘注意:不需要再配置compile dependencies
1、获取默认realm
Realm myRealm = Realm.getDefaultInstance();
if (defaultConfiguration == null) { throw new NullPointerException("No default RealmConfiguration was found. Call setDefaultConfiguration() first"); }RealmConfiguration必须通过Builder构建,RealmConfiguration的构造方法是私有的。
指定明确的RealmConfiguration可以获取指定Realm实例
Realm.getInstance(new RealmConfiguration.Builder(MainActivity.this).build());
官方代码示例
// Define you model class by extending RealmObject public class Dog extends RealmObject { private String name; private int age; // ... Generated getters and setters ... } public class Person extends RealmObject { @PrimaryKey private long id; private String name; private RealmList<Dog> dogs; // Declare one-to-many relationships // ... Generated getters and setters ... } // Use them like regular java objects Dog dog = new Dog(); dog.setName("Rex"); dog.setAge(1); // Create a RealmConfiguration that saves the Realm file in the app‘s "files" directory. RealmConfiguration realmConfig = new RealmConfiguration.Builder(context).build(); Realm.setDefaultConfiguration(realmConfig); // Get a Realm instance for this thread Realm realm = Realm.getDefaultInstance(); // Query Realm for all dogs younger than 2 years old final RealmResults<Dog> puppies = realm.where(Dog.class).lessThan("age", 2).findAll(); puppies.size(); // => 0 because no dogs have been added to the Realm yet // Persist your data in a transaction realm.beginTransaction(); final Dog managedDog = realm.copyToRealm(dog); // Persist unmanaged objects Person person = realm.createObject(Person.class); // Create managed objects directly person.getDogs().add(managedDog); realm.commitTransaction(); // Listeners will be notified when data changes puppies.addChangeListener(new RealmChangeListener<RealmResults<Dog>>() { @Override public void onChange(RealmResults<Dog> results) { // Query results are updated in real time puppies.size(); // => 1 } }); // Asynchronously update objects on a background thread realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm bgRealm) { Dog dog = bgRealm.where(Dog.class).equalTo("age", 1).findFirst(); dog.setAge(3); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { // Original queries and Realm objects are automatically updated. puppies.size(); // => 0 because there are no more puppies younger than 2 years old managedDog.getAge(); // => 3 the dogs age is updated } });
https://realm.io/docs/java/latest/#models
后续做一下文档翻译,源码解析。
欢迎扫描二维码,关注公众号
标签:
原文地址:http://blog.csdn.net/robertcpp/article/details/52097087