使用greendao存储数据过程中,我们会遇到bean嵌套的情况,这种情况怎么处理呢?我们需要用到greendao提供的PropertyConverter
来处理。
原始数据
我们假设我们存储对象是CacheBean,它有个成员变量叫SubCachedBean,代码如下:
@Entity
public class CachedBean {
private int count;
private SubCachedBean subCachedBean;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public SubCachedBean getSubCachedBean() {
return subCachedBean;
}
public void setSubCachedBean(SubCachedBean subCachedBean) {
this.subCachedBean = subCachedBean;
}
@Override
public String toString() {
return "CachedBean{" +
"count=" + count +
", subCachedBean=" + subCachedBean +
'}';
}
}
public class SubCachedBean {
private String name;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "SubCachedBean{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
此时我们只给CachedBean添加了@Entity
注解,SubCachedBean的数据是无法存储的。
使用PropertyConverter
进行转换
我们针对SubCachedBean类,创建一个对应的PropertyConverter,将其转换为String,具体如下:
public class SubCachedBeanConverter implements PropertyConverter<SubCachedBean, String> {
@Override
public SubCachedBean convertToEntityProperty(String databaseValue) {
return JSON.parseObject(databaseValue, SubCachedBean.class);
}
@Override
public String convertToDatabaseValue(SubCachedBean entityProperty) {
return JSON.toJSONString(entityProperty);
}
}
接着我们在引用SubCachedBean对象的地方,添加对应的注解即可,代码如下:
@Convert(converter = SubCachedBeanConverter.class, columnType = String.class)
private SubCachedBean subCachedBean;
同理,针对List类型的数据也一样,只需要替换下PropertyConverter后面的泛型参数即可。