我遇到greenDao和@ToMany关系的问题。当我插入数据库时,我可以轻松地获得@ToMany关系。我重新启动应用程序后出现问题,返回的列表为空。
Daily.class
@Entity
public class Daily extends BaseObservable implements Parcelable {
@Id(autoincrement = true)
private Long id;
@Unique
private String tag;
@SerializedName("summary")
@Expose
private String summary;
@SerializedName("icon")
@Expose
private String icon;
@SerializedName("data")
@Expose
@ToMany(joinProperties = {
@JoinProperty(name = "tag", referencedName = "dataTag")})
@OrderBy("id ASC")
private List<DailyData> data = new ArrayList<DailyData>();
DailyData.class
@Entity
public class DailyData extends BaseObservable implements Parcelable {
@Id(autoincrement = true)
private Long id;
@NotNull private String dataTag;
... [rest of the code]
我正在插入数据库的位置(我正在使用rxjava2获取模型)。我一直在尝试以不同的顺序插入它,但也没有任何影响。
public void insertCityToDatabase(City city) {
city.setName(cityLatLngList.get(getPosition()).getResult().getName());
city.getDailyWithoutId().setTag(city.getName());
city.getHourlyWithoutId().setTag(city.getName());
for (HourlyData hourlyData : city.getHourlyWithoutId().getHourlyDataWithoutId()) {
hourlyData.setDataTag(city.getName());
daoSession.insert(hourlyData);
}
for (DailyData dailyData : city.getDailyWithoutId().getDataWithoutId()) {
dailyData.setDataTag(city.getName());
daoSession.insert(dailyData);
}
daoSession.insert(city.getHourlyWithoutId());
daoSession.insert(city.getDailyWithoutId());
daoSession.insert(city.getCurrentlyWithoutId());
long id = daoSession.insert(city);
eventBus.post(new NewCity(id));
}
这是我的数据库Daily and DailyData,debuger Android Studio
我也尝试过做@ToMany关系 @ToMany(referencedJoinProperty =“id”)但结果是一样的。
知道为什么@ToMany关系不起作用?
答案 0 :(得分:0)
我刚刚解决了这个问题。你的Daily.class:
@SerializedName("data")
@Expose
@ToMany(joinProperties = {
@JoinProperty(name = "tag", referencedName = "dataTag")})
@OrderBy("id ASC")
private List<DailyData> data = new ArrayList<DailyData>();
和DailyData.class:
@Entity
public class DailyData extends BaseObservable implements Parcelable {
@Id(autoincrement = true)
private Long id;
@NotNull private String dataTag;
... [rest of the code]
这意味着Daily.class中的字段标记与DailyData.class中的字段dataTag有关。所以当你插入DB时:
for (DailyData dailyData : city.getDailyWithoutId().getDataWithoutId()){
dailyData.setDataTag(city.getTag());//
daoSession.insert(dailyData);
}
我以这种方式解决问题。