PersistenceConstructor argument variable name doesn't match instance variable name

后端 未结 2 1328
轻奢々
轻奢々 2021-01-13 05:41

I\'m trying to persist the following object with spring-data-mongodb version 1.1.1.RELEASE:

@Document
public static class TestObjec         


        
2条回答
  •  一整个雨季
    2021-01-13 06:16

    tl;dr

    We need to rely on constructor argument names to match field names to find out which field of the document to pull in. If you want to customize this use @Value("#root.field_name") on the constructor argument.

    Long story

    If you're using a constructor with arguments to let Spring Data instantiate the given class using this constructor we have to hand parameters to the constructor upon invocation. To find out which document field we have to hand in, we need to inspect the matching property for potential field name customization. See the following example:

    @Document
    class MyEntity {
    
      @Field("foo")
      private String myField;
    
      public MyEntity(String myField) {
        this.myField = myField;
      }
    }
    

    In this case we need to pipe the field foo into the constructor and there's no way to find out about this if we don't somehow can obtain a reference to the property. If the constructor parameter name was something different, how should we reliably find out which field value should actually be used as argument? The example you've shown in your question can never work out of the box, as your document would contain a m_property field and there's absolutely no way to find out you actually want that to be injected, except adding more explicit configuration.

    To customize this behavior you can use Spring's @Value annotation and inject a custom document field into the constructor. The document itself is available through the #root variable. So you could easily alter my sample above to:

    @Document
    class MyEntity {
    
      @Field("foo")
      private String myField;
    
      public MyEntity(@Value("#root.foo") String somethingDifferent) {
        this.myField = somethingDifferent;
      }
    }
    

    I'd strongly recommend that you add custom field names to your properties as well as you don't want to expose your property naming conventions to the database. The usage pf @Value is briefly mentioned in the reference docs but I've created a ticket to improve the docs and make this more obvious.

提交回复
热议问题