javamongodbupsertmongotemplate

MongoTemplate upsert - easy way to make Update from pojo (which user has editted)?


Here is a simple pojo:

public class Description {
    private String code;
    private String name;
    private String norwegian;
    private String english;
}

And please see the following code to apply an upsert to MongoDb via spring MongoTemplate:

Query query = new Query(Criteria.where("code").is(description.getCode()));
Update update = new Update().set("name", description.getName()).set("norwegian", description.getNorwegian()).set("english", description.getEnglish());
mongoTemplate.upsert(query, update, "descriptions");

The line to generate the Update object specifies every field of the Item class manually.

But if my Item object changes then my Dao layer breaks.

So is there a way to avoid doing this, so that all fields from my Item class are applied automatically to the update?

E.g.

Update update = new Update().fromObject(item);

Note that my pojo does not extend DBObject.


Solution

  • I ran into the same problem. In het current Spring Data MongoDB version no such thing is available. You have to update the seperate fields by hand.

    However it is possible with another framework: Morphia.

    This framework has a wrapper for DAO functionality: https://github.com/mongodb/morphia/wiki/DAOSupport

    You can use the DAO API to do things like this:

    SomePojo pojo = daoInstance.findOne("some-field", "some-value");
    pojo.setAProperty("changing this property");
    daoInstance.save(pojo);