Spring Data MongoDB 如何在实体上设置字段? [英] How are fields set on an entity by Spring Data MongoDB?

查看:60
本文介绍了Spring Data MongoDB 如何在实体上设置字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MongoRepository 类

I have a MongoRepository class

public interface UserRepository extends MongoRepository<User, Long> {

  User findById(Long id);
}

我的实体 pojo 看起来像这样

and my Entity pojo looks like this

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

  Long id;
  String name;
  Department department;
  …
}

当我调用 findBy 方法时,返回一个 User 对象.我想知道 Spring Data MongoDB 如何将 DBObject 转换为 Java 对象.我的印象是 Spring Data MongoDB 在引擎盖下使用某种映射器(Jackson?),它会根据类中的字段名称或 @Field<调用 java(Entity) 类的 setter/constructors 方法/code> 注释.但令我惊讶的是,setter 从未被调用.仅调用默认构造函数.

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.

那么字段是怎么设置的呢?我问的原因是如果调用了 setter,它会给我一个选项来设置其他一些字段.

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.

谢谢

推荐答案

Spring Data 默认为字段访问,因为访问器方法可以包含我们不想意外触发的额外逻辑.如果这是您真正想要的,您可以通过使用 @AccessType(Type.PROPERTY) 注释您的类来切换到属性访问.

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

这篇关于Spring Data MongoDB 如何在实体上设置字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆