我有这些课程:
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`)")
答案 0 :(得分:9)
我会考虑在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)
进行配置。