1. 程式人生 > >LitePal——Android資料庫框架完整使用手冊

LitePal——Android資料庫框架完整使用手冊

LitePal for Android

Logo

LitePal是一個開源的Android庫,使開發人員使用SQLite資料庫非常簡單。您無需編寫任何SQL語句就可以完成大部分資料庫操作,包括建立或升級表,增、刪、改、查操作,合計函式等。LitePal的設定也很簡單,您只許5分中國就可以將其整合到您的專案中。

現在就開始體驗吧!

功能

  • 使用物件關係對映(ORM)模式。
  • 幾乎零配置(僅有一個配置檔案,屬性值還非常少)。
  • 自動維護所有資料表(例如,建立,更改或刪除表)。
  • 支援多資料庫
  • 封裝了多種API,是開發者避免了編寫SQL語句的煩惱。
  • 超實用的查詢API。
  • 您仍可以通過編寫SQL語句進行操作,但封裝好的API會更加方便快捷。
  • 更多功能,敬請期待。

最新版下載

快速配置

1. 匯入庫

使用 Eclipse
  • 在上面的部分下載最新的jar。 或瀏覽所有版本,選擇一個下載。
  • 把jar檔案放在您Android專案的libs目錄下。
使用 Android Studio

編輯您的 build.gradle 檔案,加入如下依賴:

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

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 automatically for you. For example:
<dbname value="demo" /> --> <dbname value="demo" /> <!-- 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 automatically without concern. For example: <version value="1" /> --> <version value="1" /> <!-- 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 class="com.test.model.Magazine" /> </list> --> <list> </list> <!-- Define where the .db file should be. "internal" means the .db file will be stored in the database folder of internal storage which no one can access. "external" means the .db file will be stored in the path to the directory on the primary external storage device where the application can place persistent files it owns which everyone can access. "internal" will act as default. For example: <storage value="external" /> --> </litepal>

這是唯一的配置檔案,並且要配置的屬性也非常簡單。

  • dbname 配置該專案資料庫名稱
  • version 配置資料庫版本號。每次您要更新庫時,使其值加一。
  • list 配置對映類。
  • storage 配置資料庫檔案的儲存位置。 值為“internal” 或 “external”。

3. 配置 LitePalApplication

你不詳一直傳遞Context引數。 為了使API變得簡單,只需在AnandManManestest.xml中配置LitePalApplication,如下所示:

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

當然,您可能已經在此配置好了您自己的應用程式,如:

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

這沒關係,LitePal也可以接受。 只要在您的程式中呼叫 LitePal.initialize(context) 即可:

public class MyOwnApplication extends AnotherApplication {

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

確保儘可能早的呼叫這個方法。 最好在 onCreate() 方法中呼叫。並始終記住使用應用程式上下文作為引數。 不要使用任何活動或服務例項作為引數,否則可能會發生記憶體洩漏。

開始使用

配置成功後,您就可以使用這些功能強大的方法了。

1. 建立資料表

首先建立一個模型。例如您要建立兩個模型AlbumSong。可以按如下方式定義:

public class Album extends DataSupport {
	
    @Column(unique = true, defaultValue = "unknown")
    private String name;
	
    private float price;
	
    private byte[] cover;
	
    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.
    ...
}

然後將這些模型新增到litepal.xml對映列表中:

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

好的!資料表會在您下次操作資料庫的時候自動建立。例如,使用以下程式碼獲取SQLiteDatabase: 

SQLiteDatabase db = LitePal.getDatabase();

現在這些表會自動生成如下這樣的SQL語句:

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

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 byte[] cover;
	
    private Date releaseDate;
	
    private List<Song> songs = new ArrayList<Song>();

    // generated getters and setters.
    ...
}

已新增releaseDate欄位,並註釋了price 欄位。 然後增加litepal.xml中的版本號:

<!--
    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 automatically without concern.
    For example:    
    <version value="1" ></version>
-->
<version value="2" ></version>

資料表會在您下次操作資料庫的時候自動更新。releasedate 列會被加入到 album 表中,並且 price 列將會被刪除掉。album 表中除了被刪除的列,其他的資料都依然存在。

但是,對於一些LitePal無法處理的升級條件,升級表中的所有資料將被清除:

  • 新增一個註釋為unique = true的欄位。
  • 將欄位的註釋更改為unique = true。
  • 將欄位的註釋更改為nullable = false。

注意上述導致資料丟失的情況。

3. 儲存資料

儲存資料的API是面向物件的。從DataSupport繼承的每個模型都可以使用save()方法來儲存資料:

Album album = new Album();
album.setName("album");
album.setPrice(10.99f);
album.setCover(getCoverImageBytes());
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 and song2 插入到資料庫中並進行關聯。

4. 更新資料

最簡單的辦法,就是先通過find()方法找到待更新的記錄,並使用save()方法更新資料:

Album albumToUpdate = DataSupport.find(Album.class, 1);
albumToUpdate.setPrice(20.99f); // raise the price
albumToUpdate.save();

任何一個整合 DataSupport 類的模組都有 update() 和 updateAll() 兩個方法。您可以使用指定的ID更新單個記錄:

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

或者您也可以通過where條件來更新多條記錄:

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

5. 刪除資料

您可以使用DataSupport類中delete()這個靜態方法來刪除單條記錄:

DataSupport.delete(Song.class, id);

或者使用 deleteAll() 刪除多條記錄:

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

6. 查詢資料

通過指定ID查詢單條記錄:

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

查詢某一表中的所有記錄:

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

使用API構建複雜查詢:

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

7. 非同步操作

預設情況下,每個資料庫操作都在主執行緒上。如果您的操作可能花費很長時間,例如儲存或查詢大量記錄。 您可能需要使用非同步操作。

LitePal支援所有增、刪、改、查方法的非同步操作。如果要從後臺執行緒的song表中查詢所有記錄,請使用如下程式碼:

DataSupport.findAllAsync(Song.class).listen(new FindMultiCallback() {
    @Override
    public <T> void onFinish(List<T> t) {
        List<Song> allSongs = (List<Song>) t;
    }
});

只需使用 findAllAsync() 代替 findAll(), 並附加一個listen()方法,操作一旦完成,查詢結果將回調到onFinish()方法。

Abd非同步儲存是完全相同的:

Album album = new Album();
album.setName("album");
album.setPrice(10.99f);
album.setCover(getCoverImageBytes());
album.saveAsync().listen(new SaveCallback() {
    @Override
    public void onFinish(boolean success) {

    }
});

只需使用saveAsync()替代save()。它會將Album非同步儲存到資料庫中,儲存結果將回調到onFinish()方法。

8. 多資料庫

如果您的應用需要多個數據庫,LitePal完全支援它。 您可以在執行時建立任意數量的資料庫。 例如:

LitePalDB litePalDB = new LitePalDB("demo2", 1);
litePalDB.addClassName(Singer.class.getName());
litePalDB.addClassName(Album.class.getName());
litePalDB.addClassName(Song.class.getName());
LitePal.use(litePalDB);

這將建立一個具有singeralbumsong表的demo2資料庫。

如果您只想建立一個與litepal.xml配置相同新的資料庫,您可以使用以下命令:

LitePalDB litePalDB = LitePalDB.fromDefault("newdb");
LitePal.use(litePalDB);

您可以隨時切換回預設資料庫:

LitePal.useDefault();

您可以通過指定的資料庫名稱刪除任何資料庫:

LitePal.deleteDatabase("newdb");