简介
LitePal 是一款开源的 Android 数据库框架,采用对象映射(ORM)的模式,将平时用到的一些数据库功能进行了封装;
利用 LitePal 可以不编写 SQL 语句完成各种建表和增删改查的操作;
LitePal 也是本书作者自己开发并长期维护的;
使用方法
- 首先编辑 app/build.gradle 文件,引用开源库,具体方法是在 dependencies 闭包中添加内容如下:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'org.litepal.android:core:1.3.1' // LitePal 库
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
- 在 app/src/main 下新建目录 assets,添加文件 litepal.xml, 内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<litepal>
<dbname value = "BookStore"/>
<version value = "2"/>
<list>
<mapping class = "com.example.litepaltest.Book" />
<mapping class = "com.example.litepaltest.Category" />
</list>
</litepal>
- 在 AndroidManifest.xml 中添加配置,如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.litepaltest">
<application
android:name="org.litepal.LitePalApplication" //需要添加的内容
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
增删查改
//创建数据库
Connector.getDatabase();
//Book 类需要继承 DataSupport 类,调用 save 进行添加数据
Book book = new Book();
book.setName("The Da Vinci Code");
book.setAuthor("Dan Brown");
book.setPages(454);
book.setPrice(16.96);
book.setPress("Unknown");
book.save();
//更新数据
1 同一个对象重复赋值调用 save, 更改 book 的 price
Book book = new Book();
book.setName("The Da Vinci Code");
book.setAuthor("Dan Brown");
book.setPages(454);
book.setPrice(16.96);
book.setPress("Unknown");
book.save();
book.setPrice("10.99");
book.save();
2 调用 updateAll, 更改数据库中满足条件的 price 和 press
Book book1 = new Book();
book1.setPrice(14.95);
book1.setPress("Anchor");
book1.updateAll("name = ?", "The Da Vinci Code");
//删除数据,1 调用 delete 删除已存在的对象, 2 调用 deleteAll 函数删除满足条件的数据项
DataSupport.deleteAll(Book.class,"price < ?", "15");
//查询数据,更多的查询方法可以去查阅 DataSupport 类
List<Book> books = DataSupport.findAll(Book.class);