关于GreenDao的配置,网上是一抓一大把,这个也不多说.今天写的是在项目中使用GreenDao创建实体类的一些问题
如果实体类的结构就只有其参数,没有附带其他实体类(List<XXX> xxx或者 XXX xxx ),这种实体类创建对应的Dao文件还是很好懂的,只需要给实体类加上注解@Entry,然后点击Android Studio顶部的Build的Make Project编译下就能生成对应的Dao文件
如果是另外一种数据结构,如
{
"userId": "000",
"userName": "xxx",
"age": 20,
"family": [{
"userId": "111",
"userName": "yyy",
"age": 22
}]
}
这种数据结构在GsonFormat后的bean类
public class UserBean {
/**
* userId : 000
* userName : xxx
* age : 20
* family : [{"userId":"111","userName":"yyy","age":22}]
*/
private String userId;
private String userName;
private int age;
private List<FamilyBean> family;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<FamilyBean> getFamily() {
return family;
}
public void setFamily(List<FamilyBean> family) {
this.family = family;
}
public static class FamilyBean {
/**
* userId : 111
* userName : yyy
* age : 22
*/
private String userId;
private String userName;
private int age;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
除了最基本的@Entry
,还需要给private List<FamilyBean> family;
加上@Convert
注解,此注解可以让实体类和json字符串相互转换,此时,就需要去创建一个implements PropertyConverter
的工具
public class FamilyConverter implements PropertyConverter<List<UserBean.FamilyBean>, String> {
@Override
public List<UserBean.FamilyBean> convertToEntityProperty(String databaseValue) {
if (databaseValue == null) {
return null;
}
Type type = new TypeToken<List<UserBean.FamilyBean>>() {
}.getType();
List<UserBean.FamilyBean> arrayList = new Gson().fromJson(databaseValue, type);
return arrayList;
}
@Override
public String convertToDatabaseValue(List<UserBean.FamilyBean> entityProperty) {
if (entityProperty == null) {
return null;
} else {
String sb = new Gson().toJson(entityProperty);
return sb;
}
}
}
有了这个工具,就可以处理带有其他实体类的实体类了,
然后给需要转换的加上@Convert
注解
@Convert(columnType = String.class, converter = FamilyConverter.class)
private List<FamilyBean> family;
最外层得到实体类加上@Entry
注解
@Entity
public class UserBean {
/**
* userId : 000
* userName : xxx
* age : 20
* family : [{"userId":"111","userName":"yyy","age":22}]
*/
private String userId;
private String userName;
private int age;
@Convert(columnType = String.class, converter = FamilyConverter.class)
private List<FamilyBean> family;
}
最后使用顶部的Build
选项里的Make Project
重新构建下,GreenDao就会帮我们生成对应的Dao文件,以及实体类中的get、set和两个构造函数了