java - 使用 Mapstruct 的双向实体方法
问题描述
我有双向映射(@OneToMany Hibernate)和额外的方法来确保两个对象链接。简单的例子:
@Setter
class ParentDto {
List<ChildDto> childList;
}
@Setter
class ChildDto {
String text;
}
@Setter
class Parent {
List<Child> childList;
public void addChild(Child child) {
childList.add(child);
child.setParent(this);
}
}
@Setter
class Child {
Parent parent;
String text;
}
映射器:
@Mapper(componentModel = "spring")
public interface TestMapper {
Parent toEntity(ParentDto parentDto);
}
生成:
public class TestMapperImpl implements TestMapper {
@Override
public Parent toEntity(ParentDto parentDto) {
if ( parentDto == null ) {
return null;
}
Parent parent = new Parent();
parent.setChildList( childDtoListToChildList( parentDto.getChildList() ) );
return parent;
}
protected Child childDtoToChild(ChildDto childDto) {
if ( childDto == null ) {
return null;
}
Child child = new Child();
child.setText( childDto.getText() );
return child;
}
protected List<Child> childDtoListToChildList(List<ChildDto> list) {
if ( list == null ) {
return null;
}
List<Child> list1 = new ArrayList<Child>( list.size() );
for ( ChildDto childDto : list ) {
list1.add( childDtoToChild( childDto ) );
}
return list1;
}
主要问题:如何强制 Mapstruct 用于parent.addChild (...)
保持父级和子级列表之间的双向映射。
我有一个更复杂的结构,有多个嵌套的孩子,所以会考虑可扩展性。
解决方案
MapStruct 具有集合映射策略的概念。它允许您在映射它们时使用加法器。
例如
@Mapper(componentModel = "spring", collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
public interface TestMapper {
Parent toEntity(ParentDto parentDto);
}
推荐阅读
- django - 使用 ValidationError 和 Constraint(Django 2.2 中的新功能)时的最佳实践是什么?
- voice - 我可以添加智能插头的语音操作,这样我就可以“在 10 分钟内关闭插头”
- c - 为什么 argv[argc] 是指向 NULL 的指针?
- apache-spark - 在 Spark 中读取使用 PartitionBy 或 BucketBy 写入的文件
- csv - 关于具有给定参考/引用数量的论文数量的问题
- python - sns.Facetgrid 未显示正常分布线并忽略空间警告
- linux - 查找过去 24 小时内仅修改过一次的文件
- javascript - 删除 Div Wrapper 或更改嵌套地图中某些分组元素的类名称
- c++ - 用推导类型声明类成员
- javascript - 如何从一个js文件访问一个变量到另一个js文件,两个js文件都在android studio的不同html文件中?