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");

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