本文介绍了我可以使用Mapstruct创建Java对象/实体的DeepCopy吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JPA实体(但是这个问题通常很有趣),它由多个子类(聚合)组成.

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

我需要在数据库中创建一个与现有条目90%相同的新条目(一些业务价值,当然ID也需要不同).

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

由于我们需要mapstruct在实体和TO之间进行映射,所以我在想"mapstruct可以为我做这件事吗?"创建深层副本后,我可以简单地更新其余字段并保留对象.

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.

推荐答案

是的,您可以使用 @DeepClone :

此Javadoc包含一个示例: https://mapstruct.org/documentation/dev/api/org/mapstruct/control/MappingControl.html

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

 }

这篇关于我可以使用Mapstruct创建Java对象/实体的DeepCopy吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-19 12:22