I have these to classes:
public class Station {
@DatabaseField(foreign = true, foreignAutoCreate = true)
private OpeningTimes openingTimes;
}
public class OpeningTimes {
@DatabaseField(generatedId = true)
int _id;
}
Now OpeningTimes row is auto created, when I call createOrUpdate method on StationDao. That’s great!
I would be also thankful, if I could delete Station object and its nested object OpeningTimes automatically.
Now I have to do it this way in Station class and it seems quite confusing. Is there any more elegant way?
public void deleteFromDb(DatabaseHelper dbHelper) {
try {
openingTimes.deleteFromDb(dbHelper);
dbHelper.getStationDao().delete(this);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EDIT:
I have been trying also this, but with SQL Statement errors
@DatabaseField(foreign = true, foreignAutoCreate = true, columnDefinition="INTEGER, FOREIGN KEY(`openingTimes_id`) REFERENCES openingtimes(`_id`)")
I would consider doing this at the DAO level instead of at the persisted object level. What I recommend is creating your own
StationDaointerface and your ownStationDaoImplimplementation. The ORMLite docs an example of this.Then create your implementation which would override the
delete()method and delete any children objects. Something like the following:If you are using your own DAO then you would have to make sure it is configured using
@DatabaseTable(daoClass = StationDaoImpl.class).