學習LitePal使用

LitePal for Android

Logo

        LitePal是一個Android開源庫,它使開發者使用SQLite數據庫變得非常容易。 你可以不用寫一句SQL語句就可以完成大部分數據庫操作,包括創建表,更新表,約束操作,聚合功能等等。LitePal的安裝也相當簡單,5分鐘之內就可以將它集成到你的工程裏。


功能

  • 使用對象關係映射(ORM) 模型。
  • 幾乎零配置(只有一個配置文件,該配置文件屬性很少)。
  • 自動維護所有表格(比如創建、更改、刪除表格)。
  • 提供封裝的API,無需寫SQL語句。
  • 很棒的集羣查詢功能。
  • 依然可以選擇使用SQL,LitePal提供比原始更易用更好的API接口。

最新下載

快速安裝

1. 導入庫

使用Eclipse
  • 下載最新的jar,也可下載歷史其他版本。
  • 將jar放到工程裏的庫文件夾裏。
使用Android Studio

編輯build.gradle文件並添加以下依賴說明:

dependencies {
    compile 'org.litepal.android:core:1.3.0'
}

2. 配置litepal.xml

在工程裏的assets文件夾裏新建一個litepal.xml文件,將以下代碼拷貝進去。

<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <!--
        Define the database name of your application. 
        By default each database name should be end with .db. 
        If you didn't name your database end with .db, 
        LitePal would plus the suffix automaticly for you.
        For example:    
        <dbname value="demo" ></dbname>
    -->
    <dbname value="demo" ></dbname>

    <!--
        Define the version of your database. Each time you want 
        to upgrade your database, the version tag would helps.
        Modify the models you defined in the mapping tag, and just 
        make the version value plus one, the upgrade of database
        will be processed automaticly without concern.
            For example:    
        <version value="1" ></version>
    -->
    <version value="1" ></version>

    <!--
        Define your models in the list with mapping tag, LitePal will
        create tables for each mapping class. The supported fields
        defined in models will be mapped into columns.
        For example:    
        <list>
            <mapping class="com.test.model.Reader"></mapping>
            <mapping class="com.test.model.Magazine"></mapping>
        </list>
    -->
    <list>
    </list>
</litepal>

這是唯一的一個配置文件,裏面的屬性很簡單。

  • dbname用於配置工程的數據庫文件名。
  • version用於配置數據庫的版本信息。每次升級數據庫,該版本號加1。
  • list用於配置映射類。

3. 配置LitePalApplication

操作數據庫時需要使用到Context參數,我們不想每次都傳遞這個參數,那麼只需要在AndroidManifest.xml中配置下LitePalApplication即可,如下:

<manifest>
    <application
        android:name="org.litepal.LitePalApplication"
        ...
    >
    ...
    </application>
</manifest>

當然,你可能有自己的Application並且已經配置好,如下:

<manifest>
    <application
        android:name="com.example.MyOwnApplication"
        ...
    >
    ...
    </application>
</manifest>

沒關係,只需要將MyOwnApplication由原來的繼承Application類改成繼承LitePalApplication類就可以,如下:

public class MyOwnApplication extends LitePalApplication {
    ...
}

如果你的MyOwnApplication必須繼承另外的Application類,如AnotherApplication類,那麼你可以直接調用LitePalApplication.initialize(context)而無需繼承LiteApplication類,如下:

public class MyOwnApplication extends AnotherApplication {

    @Override
    public void onCreate() {
        super.onCreate();
        LitePalApplication.initialize(this);
    }
    ...
}

LitePalApplication.initialize(context)的調用原則是儘可能早,比如合適的調用位置是在Application的onCreate()裏調用。調用時傳遞的參數是Application的context,不要使用任何activity或service的實例作爲參數,否則可能發生內存泄漏。


開始LitePal體驗之旅

1. 創建表格

首先定義各種model,比如有兩個model:Album和Song,定義如下:

public class Album extends DataSupport {

    @Column(unique = true, defaultValue = "unknown")
    private String name;

    private float price;

    private List<Song> songs = new ArrayList<Song>();

    // generated getters and setters.
    ...
}
public class Song extends DataSupport {

    @Column(nullable = false)
    private String name;

    private int duration;

    @Column(ignore = true)
    private String uselessField;

    private Album album;

    // generated getters and setters.
    ...
}

將這兩個model添加到litepal.xml的映射表中,如下:

<list>
    <mapping class="org.litepal.litepalsample.model.Album"></mapping>
    <mapping class="org.litepal.litepalsample.model.Song"></mapping>
</list>

一旦操作數據庫時,數據庫表格將自動生成。比如使用以下代碼獲取SQLiteDatabase時,

SQLiteDatabase db = Connector.getDatabase();

將自動生成album和song兩張數據庫表格,如下:

CREATE TABLE album (
    id integer primary key autoincrement,
    name text unique default 'unknown',
    price real 
);

CREATE TABLE song (
    id integer primary key autoincrement,
    name text not null,
    duration integer,
    album_id integer
);

2. 升級表格

在LitePal中實現升級表格非常容易。

public class Album extends DataSupport {

    @Column(unique = true, defaultValue = "unknown")
    private String name;

    @Column(ignore = true)
    private float price;

    private Date releaseDate;

    private List<Song> songs = new ArrayList<Song>();

    // generated getters and setters.
    ...
}

上述代碼中,添加了releaseDate並且price標註爲ignore。

<!--
    Define the version of your database. Each time you want 
    to upgrade your database, the version tag would helps.
    Modify the models you defined in the mapping tag, and just 
    make the version value plus one, the upgrade of database
    will be processed automaticly without concern.
    For example:    
    <version value="1" ></version>
-->
<version value="2" ></version>

只需要在litepal.xml中升級版本號,那麼下次操作數據庫時表格將自動升級:ablum表中添加了releasedate列,刪除了price列,其他列的數據原封不動。

以下一些升級情況LitePal無法處理並且被升級表格裏的所有數據將被清空:

  • 添加了一個標註爲 unique = true 的屬性;
  • 修改某個屬性的標註爲 unique = true;
  • 修改某個屬性的標註爲 nullable = false;

以上情況會導致數據丟失,要格外注意。

3. 保存數據

每一個繼承DataSupport類的model都有save()方法。

Album album = new Album();
album.setName("album");
album.setPrice(10.99f);
album.save();
Song song1 = new Song();
song1.setName("song1");
song1.setDuration(320);
song1.setAlbum(album);
song1.save();
Song song2 = new Song();
song2.setName("song2");;
song2.setDuration(356);
song2.setAlbum(album);
song2.save();

以上代碼實現將album, song1和song2插入到數據庫中並建議關聯。

4. 更新數據

繼承DataSupport類的每一個model都有update()和updateAll()方法。update()可更新指定id的單條記錄,如下:

Album albumToUpdate = new Album();
albumToUpdate.setPrice(20.99f); // raise the price
albumToUpdate.update(id);

updateAll()可同時更新滿足一定條件的多條記錄,如下:

Album albumToUpdate = new Album();
albumToUpdate.setPrice(20.99f); // raise the price
albumToUpdate.updateAll("name = ?", "album");

5. 刪除數據

調用DataSupport的靜態方法delete()可刪除指定id的單條記錄:

DataSupport.delete(Song.class, id);

也可調用靜態方法deleteAll()刪除多條記錄:

DataSupport.deleteAll(Song.class, "duration > ?" , "350");

6. 查詢數據

查詢song表中指定id的單條記錄:

Song song = DataSupport.find(Song.class, id);

查詢song表中的所有記錄:

List<Song> allSongs = DataSupport.findAll(Song.class);

構建複雜的集羣查詢:

List<Song> songs = DataSupport.where("name like ?", "song%").order("duration").find(Song.class);

轉自:http://blog.csdn.net/lindonghai/article/details/50316451

發佈了29 篇原創文章 · 獲贊 10 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章