Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data mongoTemplate.save() behaviour

When you persisting a document using mongoTemplate.save() it destroys all unmapped fields in the database document.

For example, you have a collection "myDocument" with the document in the mongodb:

{
  "_id": ObjectId("552402c3186eb112488b45ea"),
  "field1": "value1",
  "field2": "value2"
}

and your domain object looks like:

public class MyDocument {
  @Id
  private String id;
  private String field1;

  // getter and setter
}

after updating your document:

MyDocument doc = myDocumentRepository.getById(<some_id>);
doc.setField1("value3");
mongoTemplate.save(doc);

you will get the document in the collection without "field2":

{
  "_id": ObjectId("552402c3186eb112488b45ea"),
  "field1": "value3"
}

It looks like unexpected behaviour and may be a real stopper when few different applications are using the same database.

Is overriding of MongoTemplate method is acceptable workaround? Any other ideas will be very appreciated.

Thanks.

update

As noted by @helmy this is how mongoTemplate.save() works and usage of update methods is preferred. But in this case I'm loosing lifecycle events that built into mongodb mapping framework. For example, validation will not works on update as it triggered by listener in onBeforeSave event...

like image 860
S2201 Avatar asked Aug 17 '16 16:08

S2201


1 Answers

That's not unexpected or surprising at all, that's how save() works -- it overwrites the entire document.

I'd suggest that you take a look at the Spring Update class to perform your updates.

like image 119
helmy Avatar answered Sep 27 '22 19:09

helmy