ForeignCollectionField的Android Ormlite升级问题

时间:2013-10-15 01:54:36

标签: android ormlite

升级我的数据库模式时,我遇到了一个没有返回行的ForeignCollectionField(ormlite 4.7)的问题。通过干净安装应用程序,可以按预期添加和显示行。

当应用程序更新为新版本时,架构会更新(请参见下文),但是当行添加到数据库时,集合不会返回添加的行。 (我可以看到数据库中存在行)

父行在更新之前存在。我需要做些什么来解决它?

定义了外国集合的父类

@DatabaseTable(tableName = "setting")
public class SettingEntity {

    @DatabaseField(generatedId = true)
    private long id;

    …

    //New field added
    @ForeignCollectionField
    private ForeignCollection<DistributionEntity> distribution;

    public SettingEntity() {
        // Required for ORMLite
    }

    public ForeignCollection<DistributionEntity> getDistribution() {
        return distribution;
    }

    public void setDistribution(ForeignCollection<DistributionEntity> distribution) {
        this.distribution = distribution;
    }
}

儿童课

@DatabaseTable(tableName = "distribution")
public class DistributionEntity {

    @DatabaseField(generatedId = true)
    private long id;
    …
    //New field added
    @DatabaseField(canBeNull = true, foreign = true, index = true, foreignAutoRefresh = true, columnDefinition = "integer references setting(id) on delete cascade")
    private SettingEntity setting;

    public void setSetting(SettingEntity setting) {

        this.setting = setting;
     }
 }

onUpgrade code

RuntimeExceptionDao<DistributionEntity, Integer> distributionDao = helper.getDistributionDao();
distributionDao.executeRaw("ALTER TABLE distribution ADD setting_id");
distributionDao.executeRaw("CREATE INDEX distribution_setting_idx ON distribution (setting_id)");

ForeignCollectionField调用分发的调试信息

enter image description here

迭代集合的代码

public ArrayList<Distribution> getDistribution() {
    getEntity().getDistribution().size();
    final ArrayList<Distribution> items = new ArrayList<Distribution>();
    final ForeignCollection<DistributionEntity> collection = getEntity().getDistribution();
    for (final DistributionEntity item : collection) {
        final Distribution dist = new Distribution(item, mContext);
        items.add(dist);
    }
    return items;
 }

NB getEntity()返回SettingEntity

的实例

感谢您花时间

1 个答案:

答案 0 :(得分:0)

更多的解决方法而不是答案,但不得不解决这个问题。通过编写代码来复制行为。

public List<DistributionEntity> getDistribution() {

    List<DistributionEntity> distributionEntities = new ArrayList<DistributionEntity>();

    try {
        DatabaseHelper helper = DatabaseHelper.getInstance();
        RuntimeExceptionDao<DistributionEntity, Integer> dao = helper.getDistributionDao();

        QueryBuilder<DistributionEntity, Integer> queryBuilder = dao.queryBuilder();
        queryBuilder.where().eq(DistributionEntity.SETTING_FIELD_NAME, Long.toString(this.getId()));
        PreparedQuery<DistributionEntity> preparedQuery = queryBuilder.prepare();
        distributionEntities = dao.query(preparedQuery);

    } catch (SQLException e) {
        e.printStackTrace();
    }

    return distributionEntities;
    //return distribution;
}

喜欢知道真正的答案是什么