英文:
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<MapStructureObjectEntity> toEntityTest(UUID mapId, MapStructureObjectDto.Update update);
List<MapStructureObjectEntity> toEntityTestList(UUID mapId, List<MapStructureObjectDto.Update> 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 -> 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
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论