LitePal采用ORM,关系映射模型,将面向对象的语言和面向关系的数据库之间建立一种映射关系,这就是对象映射模型。https://github.com/LitePalFramework/LitePal
- 添加依赖
dependencies { implementation 'org.litepal.android:java:3.0.0' }
- 在main中创建新目录--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 automatically for you.
For example:
<dbname value="demo" />
-->
<dbname value="demo" />
<!--
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 automatically without concern.
For example:
注意这里,每当你想要修改映射标签的时候,通过修改version的数值就能够实现。
<version value="1" />
-->
<version value="1" />
<!--
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 class="com.test.model.Magazine" />
</list>
-->
<list>
</list>
<!--
Define where the .db file should be. "internal" means the .db file
will be stored in the database folder of internal storage which no
one can access. "external" means the .db file will be stored in the
path to the directory on the primary external storage device where
the application can place persistent files it owns which everyone
can access. "internal" will act as default.
For example:
<storage value="external" />
-->
</litepal>
- 在AndroidMainfest.xml中添加
android:name="org.litepal.LitePalApplication"
- 主活动中添加初始化程序!
LitePal.initialize(this);
- 创建表格,建立一个Java类,写入列,注意继承LitePal,右键选择generate(生成)或者快捷键 command +N,选择get set 方法,让系统自动生成!(这里需要注意一点,最好给每一个表格都创建一个ID用于区分,查找的时候会用到)image.png
public class Album extends LitePalSupport {
@Column(unique = true, defaultValue = "unknown")
private String name;
private float price;
private byte[] cover;
private List<Song> songs = new ArrayList<Song>();
// generated getters and setters.
...
}
- 添加映射
<mapping class="com.example.peipeng.Album" /> <mapping class="org.litepal.litepalsample.model.Song" />
注意这里写的是自己的包名,且要将所有的建立的表格都要映射,否则会出现错误 - 保存数据,直接调用set() save()函数就可以
Album album = new Album();
album.setName("album");
album.setPrice(10.99f);
album.setCover(getCoverImageBytes());
album.save();
- 更新数据,通过find()函数找到对应的行,调用set() 方法设置想要修改的值,save() 保存就可以了
Album albumToUpdate = LitePal.find(Album.class, 1); albumToUpdate.setPrice(20.99f); albumToUpdate.save();
- 删除数据,调用
LitePal.delete(Song.class, id);
- 查找数据,通过使用
Song song = LitePal.find(Song.class, id);
List<Song> allSongs = LitePal.findAll(Song.class);
- 或许对于以上方法还不满足的话,可以通过adb,使用mysql语句进行修改。
网友评论