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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47929674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:43:53  来源:igfitidea点击:

ModelMapper, mapping list of Entites to List of DTO objects

javamodelmapper

提问by Gromo

I am writing simple blog web application using Spring MVC framework. I am willing to add DTOlayer to my app.

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

I decided to use ModelMapperframework for conversion from Entityobjects to DTOobjects used in my views.

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

I have just one problem. On my main page, I am showing a list of posts on my blog. In my view, it's just list of Post(Entity) objects. I want to change it to pass a list of PostDTOobjects to my view. Is there any way to map Listof Postobjects to Listof PostDTOobject with single method call? I was thinking about writing converterthat will convert this but I am not sure it's a good way to do it.

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

Also, I am using Listsof Entitiesin few more places like administrative panel or comment below every Post on my page.

此外,我还在其他几个地方使用ListsEntities,例如管理面板或我页面上每个帖子下方的评论。

Link to code of my app on GitHub repository: repository

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

采纳答案by Andrew Nepogoda

You can create util class:

您可以创建 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;
    }
}

And use it for your needs:

并根据您的需要使用它:

List<PostDTO> listOfPostDTO = ObjectMapperUtils.mapAll(listOfPosts, PostDTO.class);

回答by André Carvalho

considering you have a list of Post Entity (postEntityList) and a PostDTO class, you can try following:

考虑到您有一个 Post Entity ( postEntityList)列表和一个 PostDTO 类,您可以尝试以下操作:

use the following imports to get the desired results

使用以下导入来获得所需的结果

import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import java.lang.reflect.Type;

use the below code

使用下面的代码

Type listType = new TypeToken<List<PostDTO>>(){}.getType();
List<PostDTO> postDtoList = modelmapper.map(postEntityList,listType);

回答by karthick S

since you want to convert Entity to Dto, you can try the following one

既然你想把Entity转Dto,你可以试试下面的

List<PostDTO> entityToDto = modelMapper.map(postEntity, new TypeToken<List<PostDTO>>(){}.getType());

回答by ken4ward

Let's assume you are reading from the database, and want to convert from entities in the DB to DTOs

假设您正在从数据库中读取数据,并希望将数据库中的实体转换为 DTO

The service layer might be separated from the controller (always the best approach), then do this:

服务层可能与控制器分离(总是最好的方法),然后执行以下操作:

Service layer code:

服务层代码:

@Override
    public List<PostDTO> convertEntityToDTOList( ){
            List<Post> post = postRepository.findAll();
            Type listType = new TypeToken<List<PostDTO>>(){}.getType();
            List<PostDTO> postDTOList = modelMapper.map(post, listType);
            return postDTOList;
        }

Then in your controller, add this:

然后在您的控制器中,添加以下内容:

public ResponseEntity<?> list(){
        List<PostDTO> postDTOList = iPost.convertEntityToDTOList();
        return new ResponseEntity<>(postDTOList, HttpStatus.OK);
    }

Note that the iPost is an interface that defines method. This is it:

注意 iPost 是一个定义方法的接口。就是这个:

public interface iPost {
   List<PostDTO> convertEntityToDTOList();
}

Credits to @André Carvalho

归功于@André Carvalho

回答by Jingchao Luan

Try the following simple way:

试试下面的简单方法:

List<PostDTO> postDtoList = Arrays.asList(modelMapper.map(postEntityList, PostDTO[].class));