9

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.

2 Answers 2

17

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);

 }
0

Yes. But be careful though. If MapStruct discovers the same type on source and target it will simply take (not clone) the source type. Unless you define a method signature for it.

In other words: check the generated code carefully.

5
  • Can you expand on this? What is the "source ripe"?
    – KFleischer
    Aug 7, 2019 at 13:44
  • 1
    It's when you try to swipe 'type' on a mobile 😊. I corrected the answer
    – Sjaak
    Aug 7, 2019 at 17:04
  • Do you have an example for ths? Especially for the specific mapping that is needed. I want to avoid to write everything explicitly and was hoping for an automatism.
    – KFleischer
    Aug 8, 2019 at 9:05
  • I can't provide an example atm (have no availability over a computer). As it stands, you'll need to provide a mapping method signature for each nested type in your object tree. There has been some demand for (automated) deep cloning in the past, so check out the issues
    – Sjaak
    Aug 8, 2019 at 11:50
  • See github.com/mapstruct/mapstruct/issues/695 for supporting deep cloning
    – Filip
    Aug 11, 2019 at 6:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.