使用LitePal无法插入带有List的对象的问题

使用LitePal无法插入带有List的对象的问题

项目场景:

在使用LitePal插入一个带List的时候发现插入的List始终为空,找了好久也没有解决,后来参考了郭神的这篇文章才彻底解决:https://blog.csdn.net/guolin_blog/article/details/39207945?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-6&spm=1001.2101.3001.4242

错误的示例:

public class TopicEntity extends LitePalSupport {
    private String topic;
    private String answer;
    private List<OptionItem> list;
    
    public static class OptionItem extends LitePalSupport{
        String item;
    }

}

1.一般服务端返回的数据我们就直接用插件生成数据类了,若该类的成员变量包含其他数据类会默认创建为内部类;**(注意)**这里的OptionItem不可以写成内部类,否则在操作该内部类的时候会报:`org.litepal.exceptions.DatabaseGenerateException: can not find a class named com.example.xxxx;
2.TopicEntity里的list对象要在这里实例化,否则在操作表的时候会报空异常;

解决方案:

1.TopicEntity里内部类改为外部类,并且要在litepal,xml里加入该类的声明。

数据类:

public class TopicEntity extends LitePalSupport {
    private String topic;
    private String answer;
    private List<OptionItem> list = new ArrayList<>();


    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public String getAnswer() {
        return answer;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }

    public List<OptionItem> getList() {
        return list;
    }

    public void setList(List<OptionItem> list) {
        this.list = list;
    }
}

public class OptionItem extends LitePalSupport {
    String item;

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }
}

asset的litepal.xml文件示例:

<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <dbname value="xxxxx.db" />
    
    <version value="1" />
    
    <list>
        <mapping class="com.example.testapplication.entity.TopicEntity" />
        <mapping class="com.example.testapplication.entity.OptionItem" />

    </list>
</litepal>

2.在TopicEntity和OptionItem都要调用.save()方法才可以插入数据库;

TopicEntity topic = new TopicEntity();
topic.setTopic("xxxx");
topic.setAnswer("xxxx");
List<OptionItem> item =  topic.getList();
OptionItem option = new OptionItem();
option.setItem("xxxx");
option.save();
item.add(option);
topic.setList(item);
topic.save();

3.在查询的时候要使用LitePal.findAll(xxx.class,true);第二个参数若不写就查询不到关联表的数据;

List<TopicEntity> all = LitePal.findAll(TopicEntity.class,true);

这样就可以查询到所有数据了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值