greenDao @ToMany 关系不起作用,返回 0

greenDao @ToMany relation not working, returning 0

我对 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 关系不起作用吗?

刚才的问题我解决了。你的 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中的字段数据标签相关联。所以当你插入数据库时​​:

for (DailyData dailyData : city.getDailyWithoutId().getDataWithoutId()){
    dailyData.setDataTag(city.getTag());//
    daoSession.insert(dailyData);
}

我是这样解决问题的