Automatically delete nested objects in ORMLite

I have these classes:

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

Now the CreateTimes line is automatically created when I call the createOrUpdate method on StationDao. It's great!

I would also be grateful if I could automatically delete the Station object and its nested objects.

Now I have to do it like this in the Station class, and that seems pretty confusing. Is there a 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 am also trying to do this, but with SQL Statement errors

 @DatabaseField(foreign = true, foreignAutoCreate = true, columnDefinition="INTEGER, FOREIGN KEY(`openingTimes_id`) REFERENCES openingtimes(`_id`)") 
+4
source share
1 answer

I would think to do this at the DAO level, and not at the level of existing objects. I recommend creating your own StationDao interface and your own implementation of StationDaoImpl . ORMLite docs example of this .

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

Then create your implementation that will override the delete() method and delete any child objects. Something like the following:

 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); } } 

If you use your own DAO, you need to make sure that it is configured using @DatabaseTable(daoClass = StationDaoImpl.class) .

+8
source

Source: https://habr.com/ru/post/1398902/


All Articles