Search code examples
mongodbmorphia

Is it possible to simply update all fields in Mongo using Morphia?


We're mapping Mongo with Morphia. Morphia has many optimizations to allow updates in a document to only be applied to the fields that changed.

That's appreciated, but at this moment, I need the unoptimized case. I just want to have an entity be saved and not worry about what fields have changed.

Of course, I can simply call save(), but this invokes the lifecycle methods as if I was creating a new object.

Perhaps that is the answer: save() and have my lifecycle methods be smart enough to detect that this is a "re-save" rather than the creation of a new entity.

If there's a better approach, I would certainly appreciate hearing about it.


Solution

  • My prepersist looks something like this:

    @PrePersist
    public void prePersist() {
        creationDate = (creationDate == null) ? new Date() : creationDate;
        lastChange = (lastChange == null) ? creationDate : new Date();
    }
    

    If you want to check if an entity has already been persisted, I'd probably check the id for null values as it is autogenerated on the first save.