【问题标题】:Auto delete nested objects in ORMLite自动删除 ORMLite 中的嵌套对象
【发布时间】:2012-02-28 21:55:40
【问题描述】:

我有这些上课:

public class Station {
     @DatabaseField(foreign = true, foreignAutoCreate = true)
     private OpeningTimes openingTimes;
}

public class OpeningTimes {
     @DatabaseField(generatedId = true)
     int _id;
}

现在,当我在 StationDao 上调用 createOrUpdate 方法时,会自动创建 OpeningTimes 行。太好了!

如果我能自动删除 Station 对象及其嵌套对象 OpeningTimes,我将不胜感激。

现在我必须在 Station 类中这样做,这似乎很混乱。还有更优雅的方式吗?

public void deleteFromDb(DatabaseHelper dbHelper) {
    try {
        openingTimes.deleteFromDb(dbHelper);
        dbHelper.getStationDao().delete(this);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

编辑: 我也一直在尝试这个,但是出现 SQL 语句错误

@DatabaseField(foreign = true, foreignAutoCreate = true, columnDefinition="INTEGER, FOREIGN KEY(`openingTimes_id`) REFERENCES openingtimes(`_id`)")

【问题讨论】:

    标签: android database sqlite orm ormlite


    【解决方案1】:

    我会考虑在 DAO 级别而不是在持久对象级别执行此操作。我建议创建您自己的StationDao 接口和您自己的StationDaoImpl 实现。 ORMLite 记录了 example of this。

    public interface StationDao extends Dao<Station, Integer> {
        // we will just be overriding some of the delete methods
    }
    

    然后创建您的实现,该实现将覆盖delete() 方法并删除所有子对象。类似于以下内容:

    public class StationDaoImpl extends BaseDaoImpl<Station, Integer>
      implements StationDao {
        private final Dao<OpeningTimes, Integer> openTimesDao;
        public AccountDaoImpl(ConnectionSource connectionSource) throws SQLException {
            super(connectionSource, Station.class);
            openTimesDao = DaoManager.createDao(connectionSource, OpeningTimes.class);
        }
    
        @Override
        public int delete(Station station) throws SQLException {
            if (station.openTimes != null) {
                openTimesDao.delete(station.openTimes);
            }
            return super.delete(station);
        }
    }
    

    如果您使用自己的 DAO,则必须确保使用 @DatabaseTable(daoClass = StationDaoImpl.class) 对其进行配置。

    【讨论】:

    • 这仍然适用于PreparedDelete 吗?因为我想使用DELETE ID NOT IN 与远程数据库进行完全同步。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    相关资源
    最近更新 更多