Android 数据库框架LitePal使用详解

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

一、配置

1. 引入Jar包或源码

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

2.. 配置litepal.xml

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




    
    

    
    

    
    
        
        

    

    
    
    
    

3.配置LitePalApplication

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

Android 数据库框架LitePal使用详解_第1张图片

当然,有些程序可能会有自己的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文件,在标签中加入StudentInfo模型类的声明:


    

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

SQLiteDatabase db = Connector.getDatabase();  

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

Android 数据库框架LitePal使用详解_第2张图片 


三、插入数据

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....
}

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

        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", "存储失败");
        }

接下来看看数据库:

Android 数据库框架LitePal使用详解_第3张图片

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


他还提供了 saveAll(Collection 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 newsList = DataSupport.findAll(StudentInfo.class, ids); //根据一组id查询

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

3.where条件查询

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

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


七、创建关联表

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

Android 数据库框架LitePal使用详解_第4张图片

下面是关联的两个model

public class StudentInfo extends DataSupport {
    private String name;
    private int age;
    private int id;
    private String sex;
    private  List 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 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 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字段,只需要将StudentInfomodel)类里面的sex字段删除,然后在litepal.xml中升级版本号,那么下次操作数据库时表格将自动升级。同时将Studentinfo表里的sex列删除,其他数据不受影响。




你可能感兴趣的:(android,Android开发的点点滴滴)