Search code examples
androidormliteforeign-collection

Updating database objects that have foreign collections?


I'm trying to think of how to get around this problem. I have an ORMlite object that can belong to multiple Categories; I'm using another table (i.e. a ForeignCollection) to track many-to-many connections between my objects and categories.

The problem is if I update the object with changed categories, the new categories are added, but old ones are not removed.

In the JavaDoc for the update method of DAO I see this text:

NOTE: Typically this will not save changes made to foreign objects or to foreign collections.

My question is about the use of the word "typically." Does this mean that there IS a way through some sort of setting to make sure that updates update related foreign objects/collections?

Or should I read the sentence as if "typically" was not there, assume there is no automatic method, and that I need to run extra queries on committing each object to delete old categories?


Solution

  • The problem is if I update the object with changed categories, the new categories are added, but old ones are not removed.

    So you have an object that has a foreign collection of categories:

    @ForeignCollectionField
    ForeignCollection<Category> categories;
    

    If you run categories.add(category1) or categories.remove(category1), then the underlying collection should remove those from its associated table using a built-in DAO.

    If you are changing the category list some other way then you are going to have to remove the Category entries by hand using the categoryDao directly.

    ... about the use of the word "typically." Does this mean that there IS a way through some sort of setting to make sure that updates update related foreign objects/collections?

    Not sure why I left the word "typically" there. I think it was a blanket statement to take into account the various auto-create, auto-refresh, etc. field settings -- I'm not sure. In any case, I've removed it from the code base.

    ORMLite has no way to know if foreign objects have been changed. It does not create magic proxy objects nor sessions so that it can tell when a foreign object has been updated. You have to be explicit about what you want updated when. The documentation on foreign collections is quite explicit about it.