Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

java - Clone object without ids using mapstruct

I have an object which contains several list. is there a method to clone this object without id using mapstruct even for the nested object list in an automatic way to be able to persist it.

@Data
public class ParentDto {
  @Id
  private Long id;
  private String name;
  private List<Child1Dto> children1;
  private List<Child1Dto> children2;
}

@Data
public class Child1Dto {
  @Id
  private Long id;
  private String name;
}

@Data
public class Child2Dto {
  @Id
  private Long id;
  private String name;
}

Actual mapper

@Mapper(mappingControl = DeepClone.class)
public interface CloneParentMapper {
  @Mapping(target = "id", ignore = true)
  ParentDto cloneWithoutId(ParentDto parentDto );

  @Mapping(target = "id", ignore = true)
  Child1Dto cloneWithoutId(Child1Dto child1Dto );

  @Mapping(target = "id", ignore = true)
  Child2Dto cloneWithoutId(Child2Dto child2Dto );
}

is there a way to ignore all id without doing @Mapping(target = "id", ignore = true) on every list?

question from:https://stackoverflow.com/questions/65876174/clone-object-without-ids-using-mapstruct

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I really feel this is the best and easiest way to ignore fields.

But still if u wanna ignore fields and not mark them as ignored specifically, then you can use constructors based mappings and have a separate constructor without id field. You will have to mark this constructor as @Default.

https://mapstruct.org/documentation/stable/reference/html/#mapping-with-constructors


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...