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

丶灬走出姿态 提交于 2021-01-05 05:52:08

问题


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.


回答1:


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

 }



回答2:


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.



来源:https://stackoverflow.com/questions/57378469/can-i-create-a-deepcopy-of-an-java-object-entity-with-mapstruct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!