Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a DeepCopy of an Java Object/Entity with Mapstruct?

I have a JPA entity (but this question is interesting in general) that consists of multiple child classes (aggregation).

I need to create a new entry in the DB that is 90% identical to the existing one (a few business values and of course the IDs need to be different).

As we need mapstruct for mapping between entity and TO I was thinking "Can mapstruct do this for me?" After Creating a deep copy I could simply update the remaining fields and persist the object.

Writing a copy constructor by hand is error prone (as newly added fields could be forgotten), a generator aproach would be much appreciated.

like image 537
KFleischer Avatar asked Aug 06 '19 14:08

KFleischer


1 Answers

Yes, you can use @DeepClone:

This Javadoc contains an example: https://mapstruct.org/documentation/dev/api/org/mapstruct/control/MappingControl.html

 @Mapper(mappingControl = DeepClone.class)
 public interface CloningMapper {

     CloningMapper INSTANCE = Mappers.getMapper( CloningMapper.class );

     MyDTO clone(MyDTO in);

 }
like image 181
L. G. Avatar answered Nov 15 '22 15:11

L. G.