说明:个人直接项目测试类写博客,有个别地方删除,就不特别自个创建项目简化说明使用,可以仅仅看大概主要实现功能即可。
1、初始化(工程目录assets下创建litepal.xml文件)
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 automaticly for you.
For example:
<dbname value="demo" ></dbname>
数据库文件名
-->
<dbname value="test" />
<!--
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 automaticly without concern.
For example:
<version value="1" ></version>
数据库版本号:注意,修改table表参数或者增加table表都需要在此修改叠加版本号
-->
<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>
<mapping class="com.test.model.Magazine"></mapping>
</list>
数据库table表
-->
<list>
<mapping class="com.example.myapplication.dao.WeiTingTable" />
<mapping class="com.example.myapplication.dao.WeiTingRoadInfo" />
</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"></storage>
数据库存放目录:工程目录下/database下
-->
<storage value="external" />
</litepal>
2、Activity onCreate()初始化LitePal
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dao);
LitePal.initialize(this);
}
3、关联表bean
package com.example.myapplication.dao;
import android.util.Log;
import com.orhanobut.logger.Logger;
import org.litepal.LitePal;
import org.litepal.crud.LitePalSupport;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* 表结构:一对多关系
*/
public class WeiTingRoadInfo extends LitePalSupport {
private String adCode;
private String wholeRoadCode;
private String wholeRoadName;
private String partRoadCode;
private String partRoadName;
/**
* 提供子表获取其id
*
* @return
*/
public long getId() {
return getBaseObjId();
}
/**
* 从数据库获取子表,仅供查询不可用于操作添加更新保存子表功能(操作使用getWeiTingTableList())
*
* @return
*/
public List<WeiTingTable> getWeiTingTablesFromDb() {
String linkId = this.getClass(