objectboxobjectbox-androidobjectbox-java

Do ObjectBox ToMany containers allow duplicates and do they maintain order?


I am converting a project from Realm to ObjectBox. So far it's going well but I did run into an issue that causes some serious problems in my code. When using Realm to link to a list of other objects, I would have a member like this:

RealmList configSettings;

With ObjectBox I have changed the member to be like this:

ToMany configSettings;

This initially seemed to work until I discovered that although the ToMany class implements List, it doesn't appear to support it fully. There are two issues that I have encountered.

First is that I cannot hold duplicates in the list. After saving the object to the database and then restoring it, I find that the size of ToMany has been reduced and duplicates have been removed. This breaks some of my code because there are cases where I want duplicate entries. As an example, there may be more than one selection where the same value has been chosen. If I'm using ToMany to hold my selections then this doesn't work.

The second issue is that ToMany doesn't maintain order. There are several cases where the order of the items in the list matters. This isn't something that a sort could resolve. Often items are added to a list in some arbitrary order by the users but that order matters and needs to be maintained. If an object is saved to the database and then restored it appears that the order of the list is lost and they come back in object ID order.

In short, it appears that ToMany doesn't maintain order and doesn't allow duplicates. Is this correct? In the cases that I'm working with the relationships are many to many.

I've just tried using the ToMany container as a way to link to child objects expecting duplicates to be allowed and order to be maintained as per the List interface.


Solution

  • You are right, ToMany indeed work differently. Internally, they are not stored as a list of IDs, but as unique indexes. As such, they do not allow duplicates nor a user specified order. This design emphasizes performance, as index entries can be queried and updated extremely efficiently.

    At a first glance, I see three options:

    1. Model the relationship as its own type, similar to a many-to-many table in SQL. E.g. the type has two to-one relations to make the connection, and also an integer sequence to keep the order.

    2. Convince the ObjectBox developers to create a new list-based relation type, e.g. embedded in the object itself. It would take care of ID mapping during Sync automatically.

    3. Have a new separate property with a list of "secondary IDs". Note that you cannot just use ObjectBox IDs when using sync, as "ID mapping" happens at each device, so that IDs may differ on the devices.