Fork me on GitHub

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. 创建数据表

首先建立一个模型。例如您要建立两个模型Album和Song。可以按如下方式定义:

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

这将创建一个具有singer,album和song表的demo2数据库。

如果您只想创建一个与litepal.xml配置相同新的数据库,您可以使用以下命令:

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

您可以随时切换回默认数据库:

LitePal.useDefault();

您可以通过指定的数据库名称删除任何数据库:

LitePal.deleteDatabase("newdb");

 

posted @ 2018-03-05 22:05  郭耀华  阅读(4424)  评论(1编辑  收藏  举报