ObjectBox does not keep previous values after type migration

478 views Asked by At

We had to migrate one of the field-params in an entity from long to BigDecimal. Migration is quite smooth but there is a problem; we want to keep previous values to be set to the migrated field. But as soon as ObjectBox is initialized it defaults migrated field to the default value of the current type, in our case, to null.

Say we had:

Id (long) Name
123 Random Name

After migration we got:

Id (String) Name
null Random Name

Is there any possible way to migrate without losing values on migrated fields?

A side note: I have used a converter to keep the BigDecimal values since ObjectBox doesn't support BigDecimal

Converter class:

public class BigIntegerStringConverter implements PropertyConverter<BigInteger, String> {
    @Override
    public BigInteger convertToEntityProperty(String databaseValue) {
        return databaseValue == null ? null : new BigInteger(databaseValue);
    }

    @Override
    public String convertToDatabaseValue(BigInteger entityProperty) {
        return String.valueOf(entityProperty);
    }
}

Usage:

@Convert(converter = BigIntegerStringConverter.class, dbType = String.class)
@Uid(XXXXXXXX)
BigInteger tigerId;
3

There are 3 answers

0
Farid On BEST ANSWER

Unfortunately, type migration where old data is kept is not supported in ObjectBox.

Reference: https://github.com/objectbox/objectbox-java/issues/971

1
Uwe - ObjectBox On

ObjectBox does not support migrating existing property data to a new type. You will have to take care of this yourself, e.g. by keeping the old property and adding some migration logic.

Source: https://docs.objectbox.io/advanced/data-model-updates#changing-property-types

1
vaind On

@Farid a manual migration could look somewhat like this:

  1. add a new field to the model, with the new type you want to use, e.g. newField
  2. add code that updates all objects, reading oldField and writing the appropriate value to newField
  3. remove oldField from the model, now that all the data is migrated
  4. optionally, you can follow the docs on how to rename newField to anything you want