首页 > 系统 > Android > 正文

Android LitePal让数据库使用so easy(译)

2019-11-07 23:08:22
字体:
来源:转载
供稿:网友

Android LitePal数据库

Logo

如果英文比较好的可以点击 %20查看原文

LitePal是一个开源Android库,它允许开发者快速容易地使用SQLite数据库.%20你可以完成大多数数据库的操作,甚至而不用写一句SQL语句,%20包括创建和升级数据库表,%20crud(增删改查)操作,%20它聚集了很多功能等等.%20LitePal数据库的配置也是十分的简单,%20不到5分钟你就可以将它集成到你的项目中.%20

现在你可以愉快地开始魔幻般的体验了!

特性使用%20object-relational%20mapping%20(ORM)%20对象关系映射模式.几乎0配置(仅仅一个配置文件就可以配置好几种属性).自动维护所有表(例如创建、修改和更新表).支持复杂的数据库.封装了APIs为了避免书写SQL语句.极好流畅的查询API.你任然可以选择使用SQL语句,%20但是使用它封装好的APIs要比原生的更好和更容易.更多可以请往下浏览.最新jar包&源码下载litepal-1.4.1.jar%20(library%20contains%20*.class%20files)litepal-1.4.1-src.jar%20(library%20contains%20.class%20files%20and%20.java%20files)快速设置1.%20引入库使用Eclipse在上一个段中下载最新的jar包.或者浏览所有的版本%20点击浏览%20选择一个去下载.把jar包拷贝进到你工程的%20libs目录.使用Android%20Studio开发

编辑你的%20build.gradle%20文件并且添加以下依赖:%20%20

%20%20%20%20compile%20'org.litepal.android:core:1.4.1'2.%20配置%20litepal.xml文件

在你的工程中创建一个assets%20目录,在此目录下新建一个名为%20litepal.xml文件.%20然后把下面的代码拷贝进去.

%20%20%20%20<?xml%20version="1.0"%20encoding="utf-8"?>%20%20%20%20%20%20<litepal>%20%20%20%20<!--%20%20%20%20%20%20%20%20Define%20the%20database%20name%20of%20your%20application.%20%20%20%20%20%20%20%20%20By%20default%20each%20database%20name%20should%20be%20end%20with%20.db.%20%20%20%20%20%20%20%20%20If%20you%20didn't%20name%20your%20database%20end%20with%20.db,%20%20%20%20%20%20%20%20%20LitePal%20would%20plus%20the%20suffix%20automaticly%20for%20you.%20%20%20%20%20%20%20%20For%20example:%20%20%20%20%20%20%20%20%20%20%20%20<dbname%20value="demo"%20/>%20%20%20%20-->%20%20%20%20<dbname%20value="demo"%20/>%20%20%20%20<!--%20%20%20%20%20%20%20%20Define%20the%20version%20of%20your%20database.%20Each%20time%20you%20want%20%20%20%20%20%20%20%20%20to%20upgrade%20your%20database,%20the%20version%20tag%20would%20helps.%20%20%20%20%20%20%20%20Modify%20the%20models%20you%20defined%20in%20the%20mapping%20tag,%20and%20just%20%20%20%20%20%20%20%20%20make%20the%20version%20value%20plus%20one,%20the%20upgrade%20of%20database%20%20%20%20%20%20%20%20will%20be%20PRocessed%20automaticly%20without%20concern.%20%20%20%20%20%20%20%20%20%20%20%20For%20example:%20%20%20%20%20%20%20%20%20%20%20%20<version%20value="1"%20/>%20%20%20%20-->%20%20%20%20<version%20value="1"%20/>%20%20%20%20<!--%20%20%20%20%20%20%20%20Define%20your%20models%20in%20the%20list%20with%20mapping%20tag,%20LitePal%20will%20%20%20%20%20%20%20%20create%20tables%20for%20each%20mapping%20class.%20The%20supported%20fields%20%20%20%20%20%20%20%20defined%20in%20models%20will%20be%20mapped%20into%20columns.%20%20%20%20%20%20%20%20For%20example:%20%20%20%20%20%20%20%20%20%20%20%20<list>%20%20%20%20%20%20%20%20%20%20%20%20<mapping%20class="com.test.model.Reader"%20/>%20%20%20%20%20%20%20%20%20%20%20%20<mapping%20class="com.test.model.Magazine"%20/>%20%20%20%20%20%20%20%20</list>%20%20%20%20-->%20%20%20%20<list>%20%20%20%20</list>%20%20%20%20<!--%20%20%20%20%20%20%20%20Define%20where%20the%20.db%20file%20should%20be.%20"internal"%20means%20the%20.db%20file%20will%20be%20stored%20in%20the%20database%20folder%20of%20internal%20storage%20which%20no%20one%20can%20access.%20"external"%20means%20the%20.db%20file%20will%20be%20stored%20in%20the%20path%20to%20the%20directory%20on%20the%20primary%20external%20storage%20device%20where%20the%20application%20can%20place%20persistent%20files%20it%20owns%20which%20everyone%20can%20access.%20"internal"%20will%20act%20as%20default.%20%20%20%20%20%20%20%20For%20example:%20%20%20%20%20%20%20%20<storage%20value="external"%20/>%20%20%20%20-->%20</litepal>

这仅仅只是配置文件,%20这个配置也是非常简单.%20%20%20*%20dbname%20配置你的工程的数据库名称.%20%20*%20version%20配置数据库版本号.%20每次你想升级数据库,%20就将这个值+1.%20%20*%20list%20配置映射的JavaBean类.%20%20*%20storage%20配置你的数据库将会保存在哪里.%20internal%20和%20external%20只有这两种合法的选择.

3.%20配置LitePalApplication

如果你想要总是传递Context参数.%20为了使APIs简单,%20只要配置LitePalApplication在AndroidManifest.xml文件中配置如下即可:%20%20

%20%20%20%20<manifest>%20%20%20%20<application%20%20%20%20%20%20%20%20android:name="org.litepal.LitePalApplication"%20%20%20%20%20%20%20%20...%20%20%20%20>%20%20%20%20...%20%20%20%20</application></manifest>

当然你也可以使用你自己已有的Application里去配置,例如:

<manifest>%20%20%20%20<application%20%20%20%20%20%20%20%20android:name="com.example.MyOwnApplication"%20%20%20%20%20%20%20%20...%20%20%20%20>%20%20%20%20...%20%20%20%20</application></manifest>

好了.%20LitePal可以活跃起来了.%20只要在你的Application调用%20LitePal.initialize(context)%20就好了%20:%20%20

public%20class%20MyOwnApplication%20extends%20AnotherApplication%20{%20%20%20%20%20%20@Override%20%20%20%20public%20void%20onCreate()%20{%20%20%20%20%20%20%20%20super.onCreate();%20%20%20%20%20%20%20%20LitePal.initialize(this);%20%20%20%20}}

尽可能早的在你的Application的onCreate()方法里去调用这个.%20并且总是记得去使用application%20context参数.%20不要去使用activity%20或者%20service的实例作为参数,%20否则会导致内存泄漏问题.

我们继续

设置完之后,%20现在你可尽情地体验它的强大之处了.

1.%20创建表

首先定义models.%20假设你有两个models,%20Album%20和%20Song.%20他们的定义如下:%20%20

public%20class%20Album%20extends%20DataSupport%20{%20%20%20%20@Column(unique%20=%20true,%20defaultValue%20=%20"unknown")%20%20%20%20private%20String%20name;%20%20%20%20private%20float%20price;%20%20%20%20private%20byte[]%20cover;%20%20%20%20private%20List<Song>%20songs%20=%20new%20ArrayList<Song>();%20%20%20%20//%20generated%20getters%20and%20setters.%20%20%20%20...}public%20class%20Song%20extends%20DataSupport%20{%20%20%20%20@Column(nullable%20=%20false)%20%20%20%20private%20String%20name;%20%20%20%20private%20int%20duration;%20%20%20%20@Column(ignore%20=%20true)%20%20%20%20private%20String%20uselessField;%20%20%20%20private%20Album%20album;%20%20%20%20//%20generated%20getters%20and%20setters.%20%20%20%20...}

然后在litepal.xml%20文件的list标签内添加这2个models的全类名:

<list>%20%20%20%20<mapping%20class="org.litepal.litepalsample.model.Album"></mapping>%20%20%20%20<mapping%20class="org.litepal.litepalsample.model.Song"></mapping></list>

好了!%20下次你操作数据库的时候这些表就会生成.%20例如,%20使用下面的代码SQLiteDatabase来获取数据库实例:%20%20

SQLiteDatabase%20db%20=%20LitePal.getDatabase();

现在这些表会自动的生成,对应的SQLs语句如下:%20%20

CREATE%20TABLE%20album%20(%20%20%20%20id%20integer%20primary%20key%20autoincrement,%20%20%20%20name%20text%20unique%20default%20'unknown',%20%20%20%20price%20real,%20%20%20%20cover%20blob);CREATE%20TABLE%20song%20(%20%20%20%20id%20integer%20primary%20key%20autoincrement,%20%20%20%20name%20text%20not%20null,%20%20%20%20duration%20integer,%20%20%20%20album_id%20integer);2.%20升级表

使用LitePal升级表是非常容易的.%20只要修改你想修改的你的models的地方即可:%20%20

public%20class%20Album%20extends%20DataSupport%20{%20%20%20%20@Column(unique%20=%20true,%20defaultValue%20=%20"unknown")%20%20%20%20private%20String%20name;%20%20%20%20@Column(ignore%20=%20true)%20%20%20%20private%20float%20price;%20%20%20%20private%20byte[]%20cover;%20%20%20%20private%20Date%20releaseDate;%20%20%20%20private%20List<Song>%20songs%20=%20new%20ArrayList<Song>();%20%20%20%20//%20generated%20getters%20and%20setters.%20%20%20%20...}

一个%20releaseDate%20被添加%20并且%20price%20去添加一个被忽略的注释.%20然后在你的%20litepal.xml文件中数据库的version+1即可:%20%20

<!--%20%20%20%20Define%20the%20version%20of%20your%20database.%20Each%20time%20you%20want%20%20%20%20%20to%20upgrade%20your%20database,%20the%20version%20tag%20would%20helps.%20%20%20%20Modify%20the%20models%20you%20defined%20in%20the%20mapping%20tag,%20and%20just%20%20%20%20%20make%20the%20version%20value%20plus%20one,%20the%20upgrade%20of%20database%20%20%20%20will%20be%20processed%20automaticly%20without%20concern.%20%20%20%20For%20example:%20%20%20%20%20%20%20%20<version%20value="1"%20></version>--><version%20value="2"%20></version>

下次你操作数据库的时候这些表就会被升级,%20一个%20releasedate%20字段将会被添加到%20album%20表并且原来的price%20字段将会被移除.%20所有数据在%20album%20表中处理那些被移除的字段。%20%20

但是有一些升级表的情况LitePal不能处理升级表被清理的情况,例如:%20%20%20

添加一个属性%20unique%20=%20true.%20%20改变属性%20unique%20=%20true.%20%20把属性变为%20nullable%20=%20false.

要注意上面的这些情况将会造成数据的丢失.

3.%20保存数据

保存数据API的时候有些调整.%20每一个model将会继承DataSupport类,然后调用save()%20方法:%20%20

Album%20album%20=%20new%20Album();album.setName("album");album.setPrice(10.99f);album.setCover(getCoverImageBytes());album.save();Song%20song1%20=%20new%20Song();song1.setName("song1");song1.setDuration(320);song1.setAlbum(album);song1.save();Song%20song2%20=%20new%20Song();song2.setName("song2");song2.setDuration(356);song2.setAlbum(album);song2.save();

这是插入到album,%20song1%20和%20song2%20到数据库并且建立联系.

4.%20升级数据

最简单的一种方式是使用%20save()%20方法取升级记录,通过使用find()去查找:%20%20

Album%20albumToUpdate%20=%20DataSupport.find(Album.class,%201);albumToUpdate.setPrice(20.99f);%20//%20raise%20the%20pricealbumToUpdate.save();

每一个model都将继承于%20DataSupport,从而这些类都会有%20update()%20和%20updateAll()%20方法.%20你可以使用具体的id来修改单个记录:%20%20

Album%20albumToUpdate%20=%20new%20Album();albumToUpdate.setPrice(20.99f);%20//%20raise%20the%20pricealbumToUpdate.update(id);

或者你可以使用where条件来修改多条数据:%20%20

Album%20albumToUpdate%20=%20new%20Album();albumToUpdate.setPrice(20.99f);%20//%20raise%20the%20pricealbumToUpdate.updateAll("name%20=%20?",%20"album");5.%20删除数据

你可以删除单个数据使用DataSupport里的静态方法%20delete():%20%20

DataSupport.delete(Song.class,%20id);

或者删除多条数据使用DataSupport里的静态方法deleteAll()%20:%20%20

DataSupport.deleteAll(Song.class,%20"duration%20>%20?"%20,%20"350");6.%20查询数据

使用具体的id从song表中查询一条数据:%20%20

Song%20song%20=%20DataSupport.find(Song.class,%20id);

从song表中查询所有数据记录:%20%20

List<Song>%20allSongs%20=%20DataSupport.findAll(Song.class);

流畅的查询复杂的结构:%20%20

List<Song>%20songs%20=%20DataSupport.where("name%20like%20?",%20"song%").order("duration").find(Song.class);7.%20多数据库

如果你需要创建多个数据库,%20LitePal也可以完全的支持.%20在运行的时候你可创建尽可能多的数据库.例如:%20%20

LitePalDB%20litePalDB%20=%20new%20LitePalDB("demo2",%201);litePalDB.addClassName(Singer.class.getName());litePalDB.addClassName(Album.class.getName());litePalDB.addClassName(Song.class.getName());LitePal.use(litePalDB);

这里将创建一个demo2数据库,包含singer,%20album%20和%20**song**3个表结构.

如果你想新建一个数据库并且使用相同的配置文件litepal.xml,%20你可以这样做:%20%20

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

You%20can%20always%20switch%20back%20to%20default%20database%20with:

LitePal.useDefault();

And%20you%20can%20delete%20any%20database%20by%20specified%20database%20name:

LitePal.deleteDatabase("newdb");Translated%20Byxpf示例App

示例%20App已经发布到了Google%20Play.%20

获取:

Bugs报告

当你在使用LitePal的时候发现bug, 请报告 here. 感谢你的帮助让我们做的更好.

版本更新日志

1.4.1

Fix bug of DateSupport.count error.Fix bug of losing blob data when upgrading database.Fix other known bugs.

1.4.0

Support multiple databases.Support crud Operations for generic collection data in models.Add SQLite keyWords convert function to avoid keywords conflict.Fix known bugs.

1.3.2

Improve an outstanding speed up of querying and saving.Support to store database file in external storage.Support to mapping fields which inherit from superclass.Add findFirst() and findLast() in fluent query.Add isExist() and saveIfNotExist() method in DataSupport.

1.3.1

Support storing binary data. Byte array field will be mapped into database as blob type.Add saveFast() method in DataSupport. If your model has no associations to handle, use saveFast() method will be much more efficient.Improve query speed with optimized algorithm.

1.3.0

Add annotation functions to decalre unique, not null and default constraints.Remove the trick of ignore mapping fields with non-private modifier.Support to use annotation to ignore mapping fields with ignore = trueAdd some magical methods in DataSupport for those who understand LitePal deeper.Fix known bugs.

License

Copyright (C) Tony Green, LitePal Framework Open Source ProjectLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.

本文由Vancy翻译,由于本人水平有限,如果有什么问题,希望大家批评指正。

声明: 1.本文内容归原作者所有。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表