How are fields set on an entity by Spring Data MongoDB?

巧了我就是萌 提交于 2020-03-02 06:05:10

问题


I have a MongoRepository class

public interface UserRepository extends MongoRepository<User, Long> {

  User findById(Long id);
}

and my Entity pojo looks like this

@Document(collection = "user")
class User {

  Long id;
  String name;
  Department department;
  …
}

When I call the findBy method, a User object is returned. I want to know how does Spring Data MongoDB converts DBObject to Java object. I was under the impression that Spring Data MongoDB uses some sort of mapper (Jackson?) under the hood which would call setters/constructors method of the java(Entity) class based on the field names in the class or @Field Annotation. But to my surprise, the setters are never invoked. Only the default constructor is invoked.

Then how does the fields are set? The reason I am asking is if the setters are called, it would give me an option to set some other fields may be.

Thanks


回答1:


Spring Data defaults to field access as accessor methods can contain additional logic that we don't want to trigger by accident. If that's what you actually want though, you can switch to property access by annotating your class with @AccessType(Type.PROPERTY).




回答2:


Spring has a entity converter at the subsequent layer below it. It uses reflection to read the type of field, variables and signature. The conversion logic is generic for all data repositories. You can read about the same here

You can also introduce a custom converter be it yours or jackson, an example of it is here




回答3:


Take a look at MappingMongoConverter class - it has the logic which does all this.



来源:https://stackoverflow.com/questions/41029618/how-are-fields-set-on-an-entity-by-spring-data-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!