Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly does spring-data-mongodb handle constructors when rehydrating objects?

I have read http://static.springsource.org/spring-data/data-mongo/docs/1.1.0.RELEASE/reference/html/#mapping-chapter but cannot find the answer to the following basic spring-data-mongodb object mapping question:

If I load an instance of the following class from MongoDB:

public class Test {
    private String str1;
    private String str2;
    private Date date3;

    public Test(String str1) {
        this.str1 = str1;
        this.date3=new Date();
    }
}

I understand that the constructor Test(String str1) will be invoked with the value found in the top-level field str1 of the MongoDB document. I assume this constructor is equivalent to declaring a @PersistenceConstructor explicitly.

But what happens to the fields str2, date3 in this case? Will all fields that are not part of the constructor still be initialized, or will the str2, date3 values be lost since a PeristenceConstructor using only str1 was found?

And lastly, in what order will this happen? Will date3 be set by the constructor, then be overwritten by the previously persisted field, or vice versa?

like image 411
Karl Ivar Dahl Avatar asked Jan 31 '13 11:01

Karl Ivar Dahl


Video Answer


1 Answers

The population process is two fold and orthogonal to some degree. Mostly, you've already stated the correct behavior. The constructor is invoked to create an object instance. The parameter values are retrieved from the DBObject read and might cause a recursive creation of objects in case you hand complex objects into the constructor that need to be unmarshalled from a nested DBObject.

The next step is that your persistent fields get populated. The only difference in your case to the case with a default constructor is that we remember the field values you handed into the constructor and do not re-populate those.

The dateproperty in your example would still get set after the initialization in the constructor if the source document the object is materialized from contains a value for date.

like image 118
Oliver Drotbohm Avatar answered Oct 26 '22 23:10

Oliver Drotbohm