如何使用 MapStruct 从非可迭代对象映射到可迭代对象?

huangapple go评论57阅读模式
英文:

How to Use MapStruct mapping from non-iterable to iterable?

问题

    @Mapping(target = "mapId", source = "mapId")
    List<MapStructureObjectEntity> toEntityTest(UUID mapId, MapStructureObjectDto.Update update);
    
    @Mapping(target = "mapId", source = "mapId")
    List<MapStructureObjectEntity> toEntityTestList(UUID mapId, List<MapStructureObjectDto.Update> updateList);
英文:
List&lt;MapStructureObjectEntity&gt; toEntityTest(UUID mapId, MapStructureObjectDto.Update update);
List&lt;MapStructureObjectEntity&gt; toEntityTestList(UUID mapId, List&lt;MapStructureObjectDto.Update&gt; updateList);

I have a mapper that converts from List to List as above.

I know why it doesn't work. This is because there is a non-repeatable field called UUID, and if you exclude the UUID it works correctly.

I would like to include the UUID mapId with all data being converted.

So far, the list has been individually mapped with mapId in the Stream (or For) method.

updateList.stream().map(update -&gt; MapStructureObjectMapper.MAPPER.toEntity(mapId, update)).toList();

I don't think this is a clean way because it does the work twice.
(On top of that, the code is decentralized. Oh shit!)

Is there a convenient way to convert this to MapStruct ?

答案1

得分: 1

您可以使用映射器接口中的默认方法,该方法可以执行您期望的步骤。类似以下方式:

public interface Mapper {

MapStructureObjectEntity toEntity(MapStructureObjectDto.Update update);

default List toEntityTestList(UUID mapId, List<MapStructureObjectDto.Update> updateList) {
return updateList.stream().map(update -> {
MapStructureObjectEntity entity = toEntity(update);
entity.setUuid(mapId); // 或者根据需要执行其他步骤..
return entity;
}).toList();
}
}


<details>
<summary>英文:</summary>

You can use the default method in the mapper interface that can perform your desired steps. Something like below :

public interface Mapper {

MapStructureObjectEntity toEntity(MapStructureObjectDto.Update update);

default List<MapStructureObjectEntity> toEntityTestList(UUID mapId, List<MapStructureObjectDto.Update> updateList) {
return updateList.stream().map(update -> {
MapStructureObjectEntity entity = toEntity(update);
entity.setUuid(mapId); // Or additional steps as needed..
return entity;
}).toList();
}
}


</details>



huangapple
  • 本文由 发表于 2023年2月27日 16:53:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75578396.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定