0

I'm working on a spring based project and I’m looking if there is a clean way of mapping a request DTO with “type” field to an Entity to write to a mongodb, without using a bunch of if statements. For example the request DTO would look like:

AnimalRequestDTO.java

Public class AnimalRequestDTO {
    private AnimalType animalType;
    private String name;
    private int age;
    ...
}

And I would like to map that request to an entity automatically, so if the AnimalType was AnimalType.Monkey, it would map to the MonkeyEntity.java class or if it was AnimalType.Horse it would map to HorseEntity.java.

I was wondering if there is a useful spring tool/design pattern around something like this?

Thanks in advance

user2539621
  • 351
  • 3
  • 18
  • 3
    Spring uses Jackson by default, and Jackson has a feature called _Polymorphic type handling_. Check [this article](https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization) (it event uses animals as the example, just like you did) and [related questions](https://stackoverflow.com/questions/30362446/deserialize-json-with-jackson-into-polymorphic-types-a-complete-example-is-giv). The logic can be completely customized by modifying `AnnotationIntrospector`, but it's non trivial and you likely don't need it. – kaqqao Mar 19 '19 at 21:54
  • And if that's not what you want, and really need to map objects to objects, look into libraries like MapStruct, Orika etc. – kaqqao Mar 19 '19 at 22:00
  • As per your problem statements, it seems that you are creating separate entity for each animal type, that's is bad practice you are doing, you make single entity for each animal and make a type to differentiate it as you are doing in DTO. Why different entity for each animal? If you are making different entity then also make different DTO and then simply use *ModelMapper*, check details at http://modelmapper.org/examples/ – krishna Prasad Mar 23 '19 at 13:19

1 Answers1

1

There are several framework available for mapping between DTO to Entity and Entity to DTO. 1. Map Struct http://mapstruct.org 2. Dozer 4. Orika 5. ModelMapper 6.JMapper