domain driven design - Spring and MongoDB: Saving Value Objects in a more flat way -
for new spring application i'm designing , developing, we're using mongodb persistence layer number of technical reasons. first project i'm trying implement ddd principles, including value objects. i'm trying find best way save valueobject in fact string. using lombok's @value, spring rest controller happily parses value valueobject on restcontroller side. when saving value, gets saved in structured way on mongodb side.
for example
my vo:
@value public class personkey { private string value; }
the document i'll storing in mongodb:
@document public class persondocument { private personkey personkey; private name name; ... }
what gets saved in mongodb:
{.. "personkey": {"value": "faeeaf2"} ...}
what want:
{.. "personkey": "faeeaf2" ..}
of course minimal boilerplate code.. :-)
it seems option use abstractmongoeventlistener
onafterconvert
method modify dbobject
after conversion. unforunately, it's not possible change conversion of single field in document. custom converters used when saving entire document, not single fields. cannot use getter methods replace field access ("the fields of object used convert , fields in document. public javabean properties not used." http://docs.spring.io/spring-data/data-mongo/docs/1.4.2.release/reference/html/mapping-chapter.html). so, way achieve want through mongodb events. however, can use reflection in event handler check if field annotated @value
annotation, it's possible convert in more generic way. if @value
annotation present, replace in dbobject
it's value property.
to achieve this, need extend abstractmongoeventlistener
. can see example here onbeforesave
event handler:
update: @maartinus noticed in comments, using reflection search @value
objects not work, because it's not available in runtime (retention set source
). therefore, need introduce own annotation or interface (e.g. valueobject
) single method value()
return value of object.
Comments
Post a Comment