Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a DTO to an existing JPA entity?

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?

like image 463
dyslexit Avatar asked Oct 03 '17 01:10

dyslexit


1 Answers

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

like image 172
Sahin Yanlık Avatar answered Sep 29 '22 16:09

Sahin Yanlık