自动删除ORMLite中的嵌套对象

sea*_*kej 4 database sqlite orm android ormlite

我有这些课程:

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

public class OpeningTimes {
     @DatabaseField(generatedId = true)
     int _id;
}
Run Code Online (Sandbox Code Playgroud)

现在,当我在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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

@DatabaseField(foreign = true, foreignAutoCreate = true, columnDefinition="INTEGER, FOREIGN KEY(`openingTimes_id`) REFERENCES openingtimes(`_id`)")
Run Code Online (Sandbox Code Playgroud)

Gra*_*ray 9

我会考虑在DAO级别而不是在持久化对象级别执行此操作.我建议创建自己的StationDao界面和自己的StationDaoImpl实现.所述ORMLite文档的这个例子.

public interface StationDao extends Dao<Station, Integer> {
    // we will just be overriding some of the delete methods
}
Run Code Online (Sandbox Code Playgroud)

然后创建您的实现,它将覆盖该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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这仍然适用于`PreparedDelete`吗?因为我想使用`DELETE ID NOT IN`与远程数据库进行完全同步. (2认同)