一尘不染

ModelMapper,将实体列表映射到DTO对象列表

java

我正在使用Spring MVC框架编写简单的博客Web应用程序。我愿意DTO为我的应用添加图层。

我决定使用ModelMapper框架从Entity对象转换为DTO视图中使用的对象。

我只有一个问题。在我的主页上,我正在显示博客中的帖子列表。在我看来,这只是Post(实体)对象的列表。我想更改它以将PostDTO对象列表传递给我的视图。有没有什么办法来映射ListPost对象ListPostDTO单方法调用的对象?我当时在考虑编写将对此进行转换的转换器,但是我不确定这是否是一个好方法。

另外,我使用ListsEntities在几个地方像我的网页上管理面板或评论每一个岗位的下方。

链接到GitHub存储上我的应用程序的代码:存储库


阅读 447

收藏
2020-12-03

共1个答案

一尘不染

您可以创建util类:

public class ObjectMapperUtils {

    private static ModelMapper modelMapper = new ModelMapper();

    /**
     * Model mapper property setting are specified in the following block.
     * Default property matching strategy is set to Strict see {@link MatchingStrategies}
     * Custom mappings are added using {@link ModelMapper#addMappings(PropertyMap)}
     */
    static {
        modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
    }

    /**
     * Hide from public usage.
     */
    private ObjectMapperUtils() {
    }

    /**
     * <p>Note: outClass object must have default constructor with no arguments</p>
     *
     * @param <D>      type of result object.
     * @param <T>      type of source object to map from.
     * @param entity   entity that needs to be mapped.
     * @param outClass class of result object.
     * @return new object of <code>outClass</code> type.
     */
    public static <D, T> D map(final T entity, Class<D> outClass) {
        return modelMapper.map(entity, outClass);
    }

    /**
     * <p>Note: outClass object must have default constructor with no arguments</p>
     *
     * @param entityList list of entities that needs to be mapped
     * @param outCLass   class of result list element
     * @param <D>        type of objects in result list
     * @param <T>        type of entity in <code>entityList</code>
     * @return list of mapped object with <code><D></code> type.
     */
    public static <D, T> List<D> mapAll(final Collection<T> entityList, Class<D> outCLass) {
        return entityList.stream()
                .map(entity -> map(entity, outCLass))
                .collect(Collectors.toList());
    }

    /**
     * Maps {@code source} to {@code destination}.
     *
     * @param source      object to map from
     * @param destination object to map to
     */
    public static <S, D> D map(final S source, D destination) {
        modelMapper.map(source, destination);
        return destination;
    }
}

并将其用于您的需求:

List<PostDTO> listOfPostDTO = ObjectMapperUtils.mapAll(listOfPosts, PostDTO.class);
2020-12-03