Android 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);
原文地址:https://www.cnblogs.com/zhujiabin/p/8717314.html