自动删除ORMLite
问题描述:
嵌套的对象我有这方面的类:自动删除ORMLite
public class Station {
@DatabaseField(foreign = true, foreignAutoCreate = true)
private OpeningTimes openingTimes;
}
public class OpeningTimes {
@DatabaseField(generatedId = true)
int _id;
}
现在OpeningTimes行自动创建的,当我呼吁StationDao createOrUpdate方法。那很棒!
我也会很感激,如果我可以自动删除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`)")
答
我会考虑在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'来完成与远程数据库的完全同步。 – dzeikei 2014-03-06 23:23:51