Realm簡單入門(轉載)

轉載文章

介紹

如果你關注安卓開發的最新趨勢,你可能已經聽說過Realm。Realm是一個可以替代SQLite以及ORMlibraries的輕量級數據庫。

相比SQLite,Realm更快並且具有很多現代數據庫的特性,比如支持JSON,流式api,數據變更通知,以及加密支持,這些都爲安卓開發者帶來了方便。

在這篇快速入門教程中,你將學到Android版Realm的基礎知識。本教程我們使用的是Realm v0.84.1。

1. 添加Realm到工程

要在安卓工程中使用Realm,你需要在module的build.gradle文件中添加一個依賴:

1
compile 'io.realm:realm-android:0.84.1'

2. 創建一個Realm

一個Realm相當於一個SQLite數據庫。它有一個與之對應的文件,一旦創建將持久保存在安卓的文件系統中。

要創建一個新的Realm,你可以在任意Activity中調用靜態方法Realm.getInstance。

1
Realm myRealm = Realm.getInstance(context);

注意,調用Realm.getInstance,而沒有傳入RealmConfiguration,會創建一個叫做 default.realm的Realm文件。

如果你想向app中添加另一個Realm,必須使用一個RealmConfiguration.Builder對象,併爲Realm 文件指定一個獨有的名字。

1
2
3
4
5
6
Realm myOtherRealm =
        Realm.getInstance(
                new RealmConfiguration.Builder(context)
                        .name("myOtherRealm.realm")
                        .build()
);

3. 創建一個RealmObject

只要繼承了RealmObject類,任意JavaBean都能存儲在Realm中。不知道JavaBean是什麼?它就是一個可序列化的java類,有默認構造器,成員變量有相應的getter/setter方法。比如,下面這個類的實例就能輕鬆的存儲在一個Realm中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Country extends RealmObject {
  
    private String name;
    private int population;
  
    public Country() { }
  
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
  
    public int getPopulation() {
        return population;
    }
  
    public void setPopulation(int population) {
        this.population = population;
    }
  
}

 如果你想讓RealmObject的一個成員變量作爲主鍵,你可以使用@PrimaryKey註解。比如,這裏演示瞭如何爲Country類添加一個主鍵code:

1
2
3
4
5
6
7
8
9
10
@PrimaryKey
private String code;
  
public String getCode() {
    return code;
}
  
public void setCode(String code) {
    this.code = code;
}

4. 創建transaction

雖然從一個Realm讀取數據非常簡單(下一節有講),但是向它寫入數據就稍微複雜一點。Realm遵循 ACID (數據庫事務正確執行的四個基本要素的縮寫)規範,爲了確保原子性和一致性,它強制所有的寫入操作都在一個事務中執行。

要開始一個新的事務,使用beginTransaction方法。類似地,要結束這個事務,使用commitTransaction方法。

注:事務即英文裏面的transaction。

這裏演示瞭如何創建和保存一個Country類的實例:

1
2
3
4
5
6
7
8
9
10
11
myRealm.beginTransaction();
  
    // Create an object
    Country country1 = myRealm.createObject(Country.class); 
  
    // Set its fields
    country1.setName("Norway");
    country1.setPopulation(5165800);
    country1.setCode("NO");
  
myRealm.commitTransaction();

你可能注意到了country1並不是用Country類的構造器創建的。對於一個Realm來說,管理一個RealmObject的實例,這個實例必須用createObject方法創建。

如果你必須使用構造器,別忘了在提交事務前使用相關Realm對象的copyToRealm方法。這裏是示例:

1
2
3
4
5
6
7
8
9
// Create the object
Country country2 = new Country();
country2.setName("Russia");
country2.setPopulation(146430430);
country2.setCode("RU");
  
myRealm.beginTransaction();
    Country copyOfCountry2 = myRealm.copyToRealm(country2);
myRealm.commitTransaction();

注:copyToRealm方法還有一個很重要的作用就是可以把已經存在的對象直接拷貝進Realm數據庫。

5. 書寫查詢

Realm爲創建查詢提供了一套非常直觀和流式的API。要創建一個查詢,使用相關Realm對象的where方法並傳入你感興趣的對象的類。創建完查詢之後,你可以使用返回一個RealmResults對象的findAll方法獲取所有的結果,findAll。在下面的例子中,我們獲取並打印Country的所有對象:

1
2
3
4
5
6
7
8
RealmResults<Country> results1 =
        myRealm.where(Country.class).findAll();
  
for(Country c:results1) {
    Log.d("results1", c.getName());
}
  
// Prints Norway, Russia

Realm提供了幾個命名非常貼切的方法,比如beginsWith, endsWith,lesserThan 和 greaterThan,可以用來過濾,篩選結果。下面的代碼演示瞭如何使用greaterThan方法來獲取population(人口)大於1億的Countryobjects:

1
2
3
4
5
6
RealmResults<Country> results2 =
        myRealm.where(Country.class)
                .greaterThan("population", 100000000)
                .findAll();
  
// Gets only Russia

如果你想查詢結果被歸類,你可以使用findAllSorted方法。在它的參數中,用一個String指定被歸類field的名字,並用一個boolean指定歸類順序。

1
2
3
4
5
6
// Sort by name, in descending order
RealmResults<Country> results3 =
        myRealm.where(Country.class)
                .findAllSorted("name"false);
  
// Gets Russia, Norway

總結

在這篇快速入門中,你學到了如何在安卓項目中使用Realm。可以看到創建一個Realm數據庫、存儲查詢數據是多麼的容易。要學習更多t Realm for Android的知識,你可以查閱它的 Java 文檔






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章