您的位置:首页 > 移动开发 > Android开发

Android 数据库框架LitePal使用详解

2016-11-22 17:12 567 查看
以前一直觉得Android对SQLite数据库的操作非常简单,封装的很完善了。当我看到了郭神的LitePal框架之后我就在心理暗笑了,原来数据库还可以这样玩,真是大开眼界了。甚至你都不用写一句SQL语句,也不用考虑表之间的关联,这些都由LitePal来替你完成,配置和学习起来也是相当简单

一、配置

1. 引入Jar包或源码

首先我们需要将下载好的LitePal的jar包引入到项目当中,或者你可以直接下载源码添加依赖库。GitHub地址:https://github.com/LitePalFramework/LitePal

2.. 配置litepal.xml

接着在项目的assets目录下面新建一个litepal.xml文件,并将以下代码拷贝进去:

<?xml version="1.0" encoding="utf-8"?>
<litepal>

<!--数据库名-->
<dbname value="trip_care_db" />

<!-- 数据库版本号,升级数据库的时候只需要在此加1即可 -->
<version value="1" />

<!-- 你需要创建的表,只需要在此设定映射模型即可。
当你的数据模型结构发生变化,需要数据库也跟着改变的时候,或者添加新的映射模型的时候,需要升级你的数据库版本-->
<list>
<mapping class="com.example.sqltest.StudentInfo" />
<mapping class="com.example.sqltest.StudentInfo$Curricula" /><!--Curricula为内部类-->

</list>

<!--
keep :按类和字段名大小写作为表名和列名
upper :将所有的类和字段名称以大写的方式作为表明和列名。
lower :将所有的类和字段名称以小写的方式作为表明和列名。
-->
<cases value="keep" ></cases>
<!--
external:如果设置external,数据库文件将储存在/storage/sdcard1/Android/data/应用包名/files/databases
如果是不想被别人查看的数据,最好不要设置external
在设置external的时候别忘了加权限<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
internal:设置internal将把数据库存在应用内部文件夹,非本应用和root权限无法查看
不设置则默认internal
-->
<storage value="internal" />
</litepal>


3.配置LitePalApplication

由于操作数据库时需要用到Context,而我们显然不希望在每个接口中都去传一遍这个参数,那样操作数据库就显得太繁琐了。因此,LitePal使用了一个方法来简化掉Context这个参数,只需要在AndroidManifest.xml中配置一下LitePalApplication,所有的数据库操作就都不用再传Context了,如下所示:



当然,有些程序可能会有自己的Application,并在这里配置过了。没有关系,这时只需要修改一下MyApplication的继承结构,让它不要直接继承Application类,而是继承LitePalApplication类,就可以使用一切都能正常工作了。但是,有些程序可能会遇到一些更加极端的情况,比如说MyApplication需要继承另外一个AnotherApplication,并且这个AnotherApplication还是在jar包当中的,不能修改它的代码。这种情况应该算是比较少见了,但是如果你遇到了的话也不用急,仍然是有解释方案的。你可以把LitePal的源码下载下来,然后把src目录下的所有代码直接拷贝到你项目的src目录下面,接着打开LitePalApplication类,将它的继承结构改成继承自AnotherApplication,再让MyApplication继承自LitePalApplication,这样所有的Application就都可以在一起正常工作了。

仅仅三步,我们就将所有的配置工作全部完成了,并且这是一件一本万利的事情,自此以后,你就可以开心地体验LitePal提供的各种便利了,就让我们从建表开始吧。

二、添加表

根据对象关系映射模式的理念,每一张表都应该对应一个模型(Model),表中的每一列其实就是对应了模型类中的一个字段。

public class StudentInfo{
private String name;
private int age;
private int id;
private String sex;
}

接下来在litepal.xml文件,在<list>标签中加入StudentInfo模型类的声明:

<list>
<mapping class="com.example.sqltest.StudentInfo" />
</list>

OK,这样所有的工作就都已经完成了,现在只要你对数据库有任何的操作,StudentInfo表就会被自动创建出来。比如说LitePal提供了一个便捷的方法来获取到SQLiteDatabase的实例,如下所示:

SQLiteDatabase db = Connector.getDatabase();  

调用一下上述代码,StudentInfo表就已经创建成功了。


 

三、插入数据

LitePal中与存储相关的API其实并不多,但用法还是颇为丰富的,而且比起传统的insert()方法,使用LitePal来存储数据可以简单到让你惊叹的地步。LitePal要求所有的实体类都要继承自DataSupport这个类,因此这里我们就要把继承结构给加上才行。

public class StudentInfo extends DataSupport {

private String name;

private int age;

private int id;

private String sex;

get and set....
}

而我们想数据库保存数据只需要调用DataSupport的save()方法即可,还是上代码:

StudentInfo info = new StudentInfo("小明",13);
StudentInfo info1 = new StudentInfo("小刚",14);
if (info.save()){
Log.e("---------info","存储成功");
} else {
Log.e("---------info", "存储失败");
}
if (info1.save()){
Log.e("---------info1","存储成功");
} else {
Log.e("---------info1", "存储失败");
}

接下来看看数据库:



没错,就是这么简单,id是自动添加的,所以我们可以不用定义

他还提供了 saveAll(Collection<T> collection)方法, 将一个model集合保存到数据库

四、删除

调用DataSupport的静态方法delete()可删除指定id的单条记录:

DataSupport.delete(StudentInfo.class, id);

也可调用静态方法deleteAll()删除多条记录:

DataSupport.deleteAll(StudentInfo.class, "age >= ?" , "14");


也可调用静态方法deleteAll(Class<?> modelClass, String... conditions)删除某个表里的所有数据:

DataSupport.deleteAll(StudentInfo.class); //不传入条件参数conditions,可将整张表数据清空


五、修改

1.可以通过DataSupport的静态方法更新:

ContentValues values = new ContentValues();
values.put("name", "小李子");
DataSupport.update(StudentInfo.class, values, 4);//修改4号id的数据

2.继承DataSupport类的每一个model都有update()和updateAll()方法。update()可更新指定id的单条记录,如下:

StudentInfo info = new StudentInfo();
info.setName("小明");
info.setAge(15);
info.update(4);//修改4号id的数据

3.updateAll()可同时更新满足一定条件的多条记录如下:

StudentInfo info = new StudentInfo();
info.setSex("中性");
info.setAge(16);
info.updateAll("name = ?","小明");//修改 name=小明 的数据

六、查询

1.查询单条记录

DataSupport.find(StudentInfo.class,1); //查询id为1的单条数据
DataSupport.findFirst(StudentInfo.class); //查询StudentInfo中的第一条数据
DataSupport.findLast(StudentInfo.class); //查询StudentInfo中的最后一条数据

2.查询多条数据

long[] ids = new long[] { 1, 2, 4, 6 };
List<StudentInfo> newsList = DataSupport.findAll(StudentInfo.class, ids); //根据一组id查询

List<StudentInfo> newsList1 = DataSupport.findAll(StudentInfo.class); //查询DataSupport表的所有数据

3.where条件查询

//根据age>15作为条件查询,并按age降序排列
List<StudentInfo> newsList = DataSupport.where("age > ?", "15").order("age DESC").find(StudentInfo.class);

4.同时还LitePal还提供了原始的SQL语句查询:DataSupport.findBySQL(sql);

七、创建关联表

Student表装的是学生信息,Curricula表装的是学生选课信息,一个学生可能有很多课程,我们需要将StudentInfo表的id对应到Curricula表的StudentInfo_id字段,如下图:



下面是关联的两个model类

public class StudentInfo extends DataSupport {
private String name;
private int age;
private int id;
private String sex;
private  List<Curricula> curriculas;
get and set ....
}
public static class Curricula extends DataSupport{
public Curricula(String courses, float grade) {
this.courses = courses;
this.grade = grade;
}
private String courses;
private float grade;
get and set ....
}

只需要执行以下代码即可:

StudentInfo info = new StudentInfo();
info.setSex("中性");
info.setAge(16);
info.setName("小明");

List<StudentInfo.Curricula> curriculas = new ArrayList<>();

StudentInfo.Curricula curricula = new StudentInfo.Curricula("英语",15.5f);
StudentInfo.Curricula curricula1 = new StudentInfo.Curricula("体育",100f);

curriculas.add(curricula);
curriculas.add(curricula1);

info.setCurriculas(curriculas);

curricula.save();
curricula1.save();
if (info.save()){
Log.e("---------info","存储成功");
} else {
Log.e("---------info", "存储失败");
}

是不是很简单,只需要将他们的关系搞清楚就好了

上面的结构,通过DataSupport.find(StudentInfo.class,1);方法查询出来的数据curriculas字段是空的,这里可以加上下面的代码:

public class StudentInfo extends DataSupport {
......
public List<Curricula> getComments() {
return DataSupport.where("StudentInfo_id = ?", String.valueOf(id)).find(Curricula.class);
}
}

引用如下:

StudentInfo info = DataSupport.find(StudentInfo.class,1);
info.setCurriculas(info.getComments());

八、升级

 使用LitePal对数据库版本升级也是非常简易,比如我要删除StudentInfo表中的sex字段,只需要将StudentInfo(model)类里面的sex字段删除,然后在litepal.xml中升级版本号,那么下次操作数据库时表格将自动升级。同时将Studentinfo表里的sex列删除,其他数据不受影响。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: