Home > OS >  Morphia: Migrating existing data from Morphia 1.x to 2.x
Morphia: Migrating existing data from Morphia 1.x to 2.x

Time:09-20

I am trying to update the Morphia version from 1.x to 2.x. While doing that i have noticed that now the discriminator in the database is also changed. previously it was className="app.package.className" and now it is changed to _t="className". I found that we can explicitly mention the discriminatorKey and discriminator in the @Entity annotation as a parameter. But still I am not very sure how can i migrate existing data to support the new discriminator in version 2.x.

@Entity(discriminatorKey="className", discriminator="Unit")
public class Unit {
    @Id
    private String id;
    protected Unit() {
    }

    public String getId() {
        return this.id;
    }

    public void setId(final String id) {
        this.id = id;
    }
}

CodePudding user response:

Recently I had encountered a same situation. You can create two different Datastore of the new morphia package. The first one with legacy MapperOptions and the second with the new default MapperOptions.

Datastore datastoreLegacy = Morphia.createDatastore("dbName", MapperOptions.legacy().build());
Datastore datastoreNew = Morphia.createDatastore("dbName");

Then you can use the legacy datastore to query documents from your Unit collection and store them with the new datastore. This example shows how to perform it on every document in two statements. If the collection has a lot of data, then you should probably iterate over all documents.

List<Unit> units = datastoreLegacy.find(Unit.class).stream().collect(Collectors.toList());
datastoreNew.save(units);
  • Related