Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 525
Wheezil Avatar asked Mar 02 '17 00:03

Wheezil


2 Answers

In the meantime the required annotation has been added to spring data mongo annotations @here.

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

like image 119
Ka-Repo Avatar answered Sep 28 '22 03:09

Ka-Repo


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.

like image 41
Christoph Strobl Avatar answered Sep 28 '22 05:09

Christoph Strobl