Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto delete nested objects in ORMLite

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`)")
like image 550
sealskej Avatar asked Jan 18 '23 08:01

sealskej


1 Answers

I would consider doing this at the DAO level instead of at the persisted object level. What I recommend is creating your own StationDao interface and your own StationDaoImpl implementation. The ORMLite docs an example of this.

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

Then create your implementation which would override the delete() method and delete any children 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 are using your own DAO then you would have to make sure it is configured using @DatabaseTable(daoClass = StationDaoImpl.class).

like image 158
Gray Avatar answered Jan 20 '23 11:01

Gray