Realm is a cross-platform mobile database.It is a data persistence solution designed specifically for mobile applications. Realm store data in a universal, table-based format
It is simple as data are directly exposed as objects and queryable by code, removing the need for ORM's maintenance issues. Realm is faster than raw SQLite on common operations, while maintaining an extremely rich feature set.
3. What is Realm ?
➔
Realm is a cross-platform mobile database, released in July, 2014.
➔
It is a data persistence solution designed specifically for mobile applications.
➔
Realm store data in a universal, table-based format
➔
It is simple as data is directly exposed as objects and queryable by code, removing
the need for ORM's maintenance issues.
➔
Realm is faster than raw SQLite on common operations, while maintaining an
extremely rich feature set.
4. Installation
➔
You can install realm by adding the following class path dependency to the project
level build.gradle file.
buildscript {
repositories {
jcenter()
}
dependencies {
compile 'io.realm:realm-android:0.87.4'
}
}
5. Models
➔
Realm model classes are created by extending the RealmObject base class.
public class User extends RealmObject {
private String name;
private int age;
}
➔
Realm supports the following field types:
boolean, byte, short, int, long, float, double, String, Date and byte[].
The integer types byte, short, int, and long are all mapped to the same type (long)
within Realm.
➔
Each model class that extends RealmObject describes the schema for the table in
Realm.
6. Indexing Properties
➔ The annotation @Index will add a search index to the field.
➔ It supports indexing on the following fields: String, byte, short, Int, long,
boolean and Date
7. Primary Keys
➔ @PrimaryKey will make the field primary key.
➔ It supports string or Integer (byte, short, int, or long) as primary keys.
➔ @PrimaryKey field implicitly sets the annotation @Index.
➔ copyToRealmOrUpdate() method is used to update an object having primary
key.
➔ It looks for an existing object with the primary key and update it if found, If
no object is found a new object is created.
➔ Calling copyToRealmOrUpdate() on classes without primary keys will throw
an exception.
8. Transaction Blocks
➔
realm.beginTransaction(): Starts a transaction
➔
realm.commitTransaction(): Commits a transaction, all the changes made will be
written to disk
➔
realm.cancelTransaction(): Cancels a transaction and all the changes will be
discarded.
➔
realm.executeTransaction(): Automatically handles begin/commit, and cancel if an
error happens.
➔
Eg. 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");
}
});
9. Writes
➔
A write transaction is a transaction that is performed to update the state of your realm
object
➔
All write operations (adding, modifying, and removing objects) must be wrapped in
write transactions.
➔
Using write transactions, your data will always be in a consistent state.
➔
A write transaction can either be committed or cancelled. During the commit, all
changes will be written to disk, and the commit will only succeed if all changes can be
persisted
Eg. realm.beginTransaction();
//... add or update objects here ...
realm.commitTransaction();
10. Writes (cont...)
➔
Realm.executeTransaction() is a method that lets you exclude the begin() and
commit() transaction steps as it handles it internally.
➔
If some Exception occurs inside a transaction, then you need to cancel that
transaction in the catch block
➔
Using executeTransaction() you don’t need to call cancel transaction explicitly, it is
done automatically.
11. Creating Objects
➔
RealmObjects are strongly tied to a Realm, they should be instantiated through the
Realm directly:
Eg. realm.beginTransaction();
User user = realm.createObject(User.class); // Create a new object
user.setName("John");
user.setEmail("john@corporation.com");
realm.commitTransaction();
➔
It can also be created using realm.copyToRealm(). You can create an instance of an
object first and add it later.
Eg. 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();
➔
When using realm.copyToRealm(), only the returned object is managed by Realm, so
any further changes should be made to returned object.
12. Auto Updating Objects
RealmObjects are live and auto-updating. Modifying objects that affect the query will
be reflected in the results immediately.
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Dog myDog = realm.createObject(Dog.class);
myDog.setName("Fido");
myDog.setAge(1);
}
});
Dog myDog = realm.where(Dog.class).equalTo("age", 1).findFirst();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Dog myPuppy = realm.where(Dog.class).equalTo("age",
1).findFirst();
myPuppy.setAge(2);
}
});
myDog.getAge(); // => 2
13. Asynchronous Transactions
➔
By using an Asynchronous Transaction, Realm will execute that transaction on the
background thread.
➔
Callbacks can be provided for successful or failure conditions.
Eg. 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.
}
});
14. Queries
➔
The following conditions are supported:
between(), greaterThan(), lessThan(), greaterThanOrEqualTo() &
lessThanOrEqualTo()
equalTo() & notEqualTo()
contains(), beginsWith() & endsWith()
isNull() & isNotNull()
isEmpty() & isNotEmpty()
➔
You can also group conditions with “parentheses” to specify order of evaluation:
beginGroup() is your “left parenthesis” and endGroup() your “right parenthesis”:
Eg.
RealmResults<User> r = realm.where(User.class)
.greaterThan("age", 10) //implicit AND
.beginGroup()
.equalTo("name", "Peter")
.or()
.contains("name", "Jo")
.endGroup()
.findAll();
15. Aggregation Queries
➔
A RealmResults has various aggregation methods:
RealmResults<User> results = realm.where(User.class).findAll();
long sum = results.sum("age").longValue();
long min = results.min("age").longValue();
long max = results.max("age").longValue();
double average = results.average("age");
long matches = results.size();
Deletion Queries
➔ You can delete the results of a query from the Realm:
RealmResults<Dog> results = realm.where(Dog.class).findAll();
// All changes to data must happen in a transaction
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
results.removeLast(); // remove last object
results.remove(5); // remove a single object
Dog dog = results.get(2);
results.remove(dog);
}
});
16. Configuring Realm
➔
Realms are equivalent of a database: they contain different kinds of objects.
➔
RealmConfiguration object is used to control all aspects of how a Realm is created.
The minimal configuration usable by Realm is:
RealmConfiguration config = new RealmConfiguration.Builder().build();
The above configuration will point to a file calles default.realm
➔ The RealmConfiguration can be saved as a default configuration.
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Realm realm = Realm.getDefaultInstance();
// ... Do something ...
realm.close();
}
}
17. In Memory Realm
➔
To define an instance for an un-persisted in-memory Realm:
RealmConfiguration myConfig = new RealmConfiguration.Builder()
.name("myrealm.realm")
.inMemory()
.build();
Realm.getInstance(config);
Setting this will create an in-memory Realm instead of saving it to disk.
In-memory Realms might still use disk space if memory is running low, but all files
created by an in-memory Realm will be deleted when the Realm is closed.