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对应的,又改如何处理?
网友评论