SprinBoot DTO to Entity (viceversa) conversion using JMapper

Viewed 521

I'm using SpringBoot and I would like to write the adapter to have the conversion utility from DTOs to Entities and vice versa.

I'm exploring some Converter tools like JMapper, ObjectMapper, etc Into my converters I need to have some custom conversions (for example from Enum to different Enum and other types).

I'm not able to find into the documentation if there is a way define custom converter method using JMapperAPI. Is there this possibility?

I saw that it's possible to use an annotation @JMapConversion on the custom method but I prefer to have the conversion logic into my adapter so I prefer to don't use this annotation.

Suggestions?

1 Answers

I suppose you have these classes:

  • DtoRequest
  • Enttiy
  • DtoResponse

You can create a new class Common which contains common fields after that extend this class by all other classes.

class Common { //...common fields}
class DtoRequest extend Common { //fields in request but not in the enitty}
class Enttiy extend Common { //fields in entity but not in the dto classes}
class DtoResponse extend Common { //fields in response not not in the enitty}

You can use copyProperties from spring in order to automatically map common values. Other values can be mapped manually.

BeanUtils.copyProperties(Object source, Object target, Common.class)
// DtoRequest --> Enttiy
// Enttiy --> DtoResponse
Related