Wheezil
Wheezil

Reputation: 3462

spring-data-mongodb equivalent of @JsonUnwrapped in Jackson

I would like to use a composition pattern to reuse common portions of classes as I can do in Jackson with @JsonUnwrapped, without adding an extra level of structure in the mongodb document, for example:

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

So that when B or C is stored in mongodb it looks like:

{ x:123, y:456 }

instead of

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

Unfortunately, I'm not finding an appropriate annotation in spring-data-mongodb annotations or core spring data annotations. Does one exist? I understand that this necessarily makes polymorphism of the A sub-structure impossible.

Upvotes: 9

Views: 1341

Answers (2)

Ka-Repo
Ka-Repo

Reputation: 46

Support for this has since been added in Spring Data MongoDB 3.2 with the @Unwrapped annotation. This is in the reference documentation under Unwrapped Types Mapping.

Usage:

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"
}

Upvotes: 3

Christoph Strobl
Christoph Strobl

Reputation: 6736

Spring Data MongoDB does not evaluate Jackson annotations. The best chance to get this working is by providing a CustomConverter tailored to your needs.

However there's an open ticket (DATAMONGO-1902) to support flattening out/read nested structures into/from the parent document you may vote for.

Upvotes: 1

Related Questions