简体   繁体   中英

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. It looks like Spring is automatically persisting both fields and getters to MongoDB.

In general I would like it to only persist getters and never automatically persist fields. I know about @Transient for one-off annotations, but would like to configure this as general behavior.

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. To my knowlegde only fields are persisted. (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))

or an short example:

If you have an Pojo like this:

@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.

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). You could write some code here that uses the declared getters of your class and maps them onto fields of your document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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