spring-data-mongodb 相当于 Jackson 中的 @JsonUnwrapped

spring-data-mongodb equivalent of @JsonUnwrapped in Jackson

我想使用组合模式来重用 类 的公共部分,就像我在 Jackson 中使用 @JsonUnwrapped 所做的那样,而无需在 mongodb 文档中添加额外的结构级别,因为示例:

class A {
  int x; int y;
}
class B { 
  @JsonUnwrapped
  A a;
}
class C { 
  @JsonUnwrapped
  A a;
}

因此,当 B 或 C 存储在 mongodb 中时,它看起来像:

{ x:123, y:456 }

而不是

{ a: { _class:"A", x:123, y:456 } }

很遗憾,我在 spring-data-mongodb annotations or core spring data annotations 中找不到合适的注释。一个存在吗?我知道这必然使 A 子结构的多态性成为不可能。

Spring 数据 MongoDB 不评估 Jackson 注释。实现这一目标的最佳机会是提供 CustomConverter 适合您的需求。

然而,有一个开放票证 (DATAMONGO-1902) 支持展平 out/read 嵌套结构 into/from 您可以投票支持的父文档。

与此同时,所需的注释已添加到 spring 数据 mongo 注释 @here.

用法:

class User {

    @Id
    String userId;

    @Unwrapped(onEmpty = Unwrapped.OnEmpty.USE_NULL) 
    UserName name;
}

class UserName {

    String firstname;

    String lastname;

}

{
  "_id" : "1da2ba06-3ba7",
  "firstname" : "Emma",
  "lastname" : "Frost"
}