How to map a DTO to an existing JPA entity?

dyslexit picture dyslexit · Oct 3, 2017 · Viewed 23.1k times · Source

I'm trying to map a Java DTO object to an existing JPA entity object without having to do something like the following:

public MyEntity mapToMyEntity(SomeDTO dto, MyEntity entity) {
    entity.setField1(dto.getField1());
    entity.setField2(dto.getField2());
    ...
    entity.setField20(dto.getField20());

    return entity;
}

Up to now I've been using ModelMapper like so: MyEntity entity = modelMapper.map(dto, SomeDTO.class);, but what I'm trying to do instead is map to an existing entity object rather than creating a new entity object from a DTO. I've looked through the ModelMapper manual and couldn't find how to map without creating a new object. Am I stuck adding each member variable manually for each entity object I might have?

Answer

Sahin Yanlık picture Sahin Yanlık · Oct 3, 2017

You can use dozer mapper or gson.

DozerMapper ex:

Mapper mapper = DozerBeanMapperBuilder.createDefault();
DestinationObject destObject = mapper.map(sourceObject,DestinationClassName.class);

You can check github page for more information