问题
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