简体   繁体   English

如何禁用Spring Data MongoDB文档的字段映射?

[英]How do I disable mapping of fields for Spring Data MongoDB documents?

I am using Spring Data to persist POJOs as documents in MongoDB via MongoRepository. 我使用Spring Data通过MongoRepository将POJO作为文档保存在MongoDB中。 It looks like Spring is automatically persisting both fields and getters to MongoDB. 看起来Spring会自动将字段和getter都持久化到MongoDB。

In general I would like it to only persist getters and never automatically persist fields. 一般来说,我希望它只保留getter并且永远不会自动持久化字段。 I know about @Transient for one-off annotations, but would like to configure this as general behavior. 我知道@Transient的一次性注释,但是想将其配置为一般行为。

Is there a way to configure this? 有没有办法配置这个?

It can be done by writing your own custom Converters. 可以通过编写自己的自定义转换器来完成。

You state in your question that spring data mongodb persist both , fields and getters. 你用你的问题春天MongoDB的数据坚持,字段和getter。 To my knowlegde only fields are persisted. 对于我的knowlegde, 只有字段是持久的。 (See 11.1 in the docu: http://docs.spring.io/spring-data/mongodb/docs/1.6.3.RELEASE/reference/html/#mapping-conventions (1.6.3 is the version shipped by spring-boot 1.2.6, but it is the same in older versions and 1.8.0)) (见实况11.1: http://docs.spring.io/spring-data/mongodb/docs/1.6.3.RELEASE/reference/html/#mapping-conventions (1.6.3是弹簧附带的版本启动1.2.6,但旧版本和1.8.0相同)))

or an short example: 或一个简短的例子:

If you have an Pojo like this: 如果你有这样的Pojo:

@Document
public class MyClass
{
    private ObjectId id;

    private String foo = "foo";

    public String getBar()
    {
        return "bar";
    }
}

and a Repository like this: 和这样的存储库:

public interface MyClassRepository extends MongoRepository<MyClass,ObjectId>
{
}

and an application code like this: 和这样的应用程序代码:

public static void main(String[] args) throws UnknownHostException
{
    ApplicationContext ctx = SpringApplication.run(NewClass.class, args);
    MongoTemplate mongoTemplate = ctx.getBean(MongoTemplate.class);
    MyClass myClass = new MyClass();
    mongoTemplate.save(myClass);
    MyClassRepository myClassRepository = ctx.getBean(MyClassRepository.class);
    myClassRepository.save(myClass);
}

the following document is save (once by the template and then again by the repository: 保存以下文档(一次由模板保存,然后由存储库再次保存:

{
    "_id" : ObjectId("560b97edcb60110890ab7119"),
    "_class" : "sandbox.MyClass",
    "foo" : "foo"
}

So, the getter was not used for conversion of the MyClass object. 因此,getter不用于转换MyClass对象。

The same documentation as cited above shows you how to write your own Converter and how to register it to the MongoTemplate (section 8.10). 上面引用的相同文档向您展示了如何编写自己的Converter以及如何将其注册到MongoTemplate(第8.10节)。 You could write some code here that uses the declared getters of your class and maps them onto fields of your document. 您可以在这里编写一些代码,使用您声明的类的getter并将它们映射到文档的字段中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM