MongoTemplate upsert - 从 pojo(哪个用户编辑过)进行更新的简单方法? [英] MongoTemplate upsert - easy way to make Update from pojo (which user has editted)?

查看:109
本文介绍了MongoTemplate upsert - 从 pojo(哪个用户编辑过)进行更新的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的 pojo:

Here is a simple pojo:

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

并且请参阅以下代码以通过 spring MongoTemplate 将 upsert 应用到 MongoDb:

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");

生成Update 对象的行手动指定Item 类的每个字段.

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

但是如果我的 Item 对象发生变化,那么我的 Dao 层就会中断.

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

那么有没有办法避免这样做,以便我的 Item 类中的所有字段都自动应用于更新?

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

例如

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

请注意,我的 pojo 没有扩展 DBObject.

Note that my pojo does not extend DBObject.

推荐答案

我遇到了同样的问题.在当前的 Spring Data MongoDB 版本中,没有这样的东西可用.您必须手动更新单独的字段.

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.

但是使用另一个框架是可能的:Morphia.

However it is possible with another framework: Morphia.

这个框架有一个 DAO 功能的包装器:https://github.com/mongodb/morphia/wiki/DAOSupport

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

您可以使用 DAO API 执行以下操作:

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);

这篇关于MongoTemplate upsert - 从 pojo(哪个用户编辑过)进行更新的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆