greendao存储嵌套数据(一)

greendao存储嵌套数据(一)
greendao存储嵌套数据(二)

如果有下面这样一个类,想要插入数据

@Entity
public class ABean {

    private int first;

    private BBean bBean;
}

@Entity
public class BBean {
     private int second;
}

正常的通过greendao,在编译时,就会报错;
需要将ABean中的BBean继续转换,转成String类型;代码如下:

@Entity
public class ABean {

    private int first;

    @Convert(converter = BBeanConvert.class, columnType = String.class)
    private BBean bBean;

    @Generated(hash = 316914447)
    public ABean(int first, BBean bBean) {
        this.first = first;
        this.bBean = bBean;
    }

    @Generated(hash = 1883429528)
    public ABean() {
    }

    public int getFirst() {
        return this.first;
    }

    public void setFirst(int first) {
        this.first = first;
    }

    public BBean getBBean() {
        return this.bBean;
    }

    public void setBBean(BBean bBean) {
        this.bBean = bBean;
    }

}
public class BBeanConvert  implements PropertyConverter<BBean, String> {

    @Override
    public BBean convertToEntityProperty(String databaseValue) {
        return JSONUtil.fromJson(databaseValue, BBean.class);
    }

    @Override
    public String convertToDatabaseValue(BBean entityProperty) {
        return JSONUtil.toJson(entityProperty);
    }
}

然后插入数据:

 BBean bBean = new BBean();
        bBean.setSecond(2);
        ABean aBean = new ABean();
        aBean.setBBean(bBean);
        aBean.setFirst(1);

        DaoSession daoSession = CalendarSQLiteManager.getInstance().getDaoSession();
        daoSession.insert(aBean);

查看数据库:


另外:
1.如果ABean中存在一个List<BBean>属性应该如何处理:
参考:https://www.jianshu.com/p/c697b2de86f2
2.如果希望BBean的数据单独存在BBean的表中,对应的外键id是ABean对应的,又改如何处理?

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 使用greendao存储数据过程中,我们会遇到bean嵌套的情况,这种情况怎么处理呢?我们需要用到greendao...
    tinyvampirepudg阅读 610评论 1 3
  • 一、简述 众所周知,移动端(不管是Android还是iOS)使用的数据库是Sqlite,这种小型的数据库很适合移动...
    GitLqr阅读 2,227评论 2 10
  • 前言 Android开发中,经常用到的三种本地数据持久化的方式为: SharedPreference 文件存储的方...
    MorisWang阅读 1,060评论 1 5
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 13,079评论 2 59
  • 前言 最近的项目需要使用到数据库,本来想用Sqlite数据来做的,但是听同事说使用Greendao数据库是真的好用...
    Smile__EveryDay阅读 3,648评论 2 7