Search code examples
ormliteforeign-collection

OrmLite – Prevent automatic database changes when adding to or removing from a ForeignCollection


Currently, I am using OrmLite and I have three objects A, B, and C. A contains a ForeignCollection of B, and B contains a ForeignCollection of C. Anytime I add an element to the ForeignCollections an insert statement is instantly executed. A delete statement is instantly executed anytime I remove an element.

I would like to add/remove without the statements being executed until I either create or update A. Is this possible?


Solution

  • I would like to add/remove without the statements being executed until I either create or update A. Is this possible?

    There is no way to do this currently. The lazy-loaded collection doesn't even store items in itself so the idea of caching changes for later is not possible.

    You could do this on your own however. You could keep a list of items in the entity and then override the dao.create(...) and dao.update(...) methods to call collection.addAll(...) if there are any cached items in your special collection.

    private List<Item> foreignItemsToAdd;
    ...
    private void addForeignItem(Item item) {
       if (foreignItemsToAdd == null) {
           foreignItemsToAdd = new ArrayList<Item>();
       }
    }
    

    Then the dao would have something like:

    @Override
    public int create(ParentItem parent) throws SQLException {
        if (parent.getForeignItemsToAdd() != null) {
            parent.getForeignItems().addAll(parent.getForeignItemsToAdd());
        }
        return super.create(parent);
    }