使用 SpringBoot 作为 REST 响应,我的 Controller 必须返回 MenuDTO
列表,它是 SimpleMenuDTO
和 TastingMenuDTO
的父类。
我正在使用 ModelMapper 将实体映射到 DTO。
public abstract class MenuEntity {
private String name;
private String description;
private RestaurantEntity restaurant;
}
public class SimpleMenuEntity extends MenuEntity {
private final Set<MenuSectionEntity> sections = new HashSet<>();
}
public class TastingMenuEntity extends MenuEntity {
private BigDecimal price;
private final Set<ProductEntity> products = new HashSet<>();
}
public class MenuDTO {
private String name;
private String description;
private char menuType;
private Long restaurantId;
}
我该如何处理这种情况?
我能够更改实体和 DTO。
更新
这里的主要问题是如何在运行时动态映射 SimpleMenuEntity
和 TastingMenuEntity
列表。
最佳答案
我明白了。 我必须像这样配置映射器:
mapper.createTypeMap(TastingMenuEntity.class, MenuDTO.class)
.setConverter(mappingContext -> mapper.map(mappingContext.getSource(), TastingMenuDTO.class));
mapper.createTypeMap(SimpleMenuEntity.class, MenuDTO.class)
.setConverter(mappingContext -> mapper.map(mappingContext.getSource(), SimpleMenuDTO.class));
因此,最终的映射方法如下:
public MenuDTO map(MenuEntity entity) {
ModelMapper mapper = new ModelMapper();
mapper.createTypeMap(TastingMenuEntity.class, MenuDTO.class)
.setConverter(mappingContext -> mapper.map(mappingContext.getSource(), TastingMenuDTO.class));
mapper.createTypeMap(SimpleMenuEntity.class, MenuDTO.class)
.setConverter(mappingContext -> mapper.map(mappingContext.getSource(), SimpleMenuDTO.class));
return mapper.map(entity, MenuDTO.class);
}
关于java - 如何在Java中动态映射同一父类的子对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58793150/