Search code examples
javaormormliteforeign-collection

ORMLite - force read objects to have same identity


I'm reading a hierarchy of objects with ORMLite. It is shaped like a tree, parents have a @ForeignCollection of 0+ children, and every child refers to its parent with @DatabaseField(foreign=true). I'm reading and saving the whole hierarchy at once.

As I'm new to ORM in general, and to ORMLite as well, I didn't know that when objects with the same ID in the database are read, they won't be created as the actually same object with the same Identity, but as several duplicates having the same ID. Meaning, I'm now facing the problem that (let's say "->" stands for "refers to") A -> B -> C != C -> B -> A.

I was thinking to solve the problem by manually reading them through the provided DAOs and puting them together by their ID, assuring that objects with the same ID have the same identity.

Is there are ORMLite-native way of solving this? If yes, what is it, if not, what are common ways of solving this problem? Is this a general problem of ORM? Does it have a name (I'd like to learn more about it)?

Edit:

My hierarchy is so that one building contains several floors, where each floor knows its building, and each floor contains several zones, where every zone knows its floor.


Solution

  • Unfortunately there is not a ORMLite-native way of solving this problem. More complex ORM systems (such as Hibernate) have caching layers which are there specifically for this reason. ORMLite does not have a cache layer so it doesn't know that it just returned an object with the same id "recently". Here's documentation of Hibernate caching:

    http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html

    However, ORMLite is designed to be Lite and cache layers violate that designation IMO. About the only [unfortunate] solution that I see to your issue in ORMLite is to do what you are doing -- rebuilding the object tree based on the ids. If you give more details about your hierarchy we may be able to help more specifically.


    So after thinking about your case a bit more @riwi, it occurred to me that if you have a Building that contains a collection of Floors, there is no reason why the Building object on each of the Floors in the collection cannot be set with the parent Building object. Duh. ORMLite has all of the information it needs to make this happen. I implemented this behavior and it was released in version 4.24.

    Edit:

    As of ORMLite version 4.26 we added an initial take on an object-cache that can support the requested features asked for. Here are the docs:

    http://ormlite.com/docs/object-cache