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.
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"
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With