java - 如何在Java中动态映射同一父类的子对象列表

标签 java rest design-patterns domain-driven-design

使用 SpringBoot 作为 REST 响应,我的 Controller 必须返回 MenuDTO 列表,它是 SimpleMenuDTOTastingMenuDTO 的父类。

我正在使用 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。

更新 这里的主要问题是如何在运行时动态映射 SimpleMenuEntityTastingMenuEntity 列表。

最佳答案

我明白了。 我必须像这样配置映射器:

        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/

相关文章:

design-patterns - 包装器、桥接器和中介器之间有什么区别?

java - 生成动态 sql SELECT 语句

java - 我可以在将对象与另一个数组进行比较时更改对象的一个​​值吗?

c++ - Swagger cpprest 第三方

java - 通过 Id 删除实体时 Hibernate InvalidDataAccessApiUsageException

javascript - 如何在 JavaScript 中将 DOM View 逻辑与 DOM 事件( Controller ?)逻辑分开?

java - 使用 Java (apache commons io) 删除文件时出现问题

java - Blueprism - Java 弹出窗口不会返回控件

java - 使用 Apache Camel 发送 POST 请求

c++ - cpp中如何根据数据类型将数据推送到不同的队列?