ModelMapper, mapping list of Entites to List of DTO objects

前端 未结 5 1213
深忆病人
深忆病人 2021-02-01 23:49

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

I decided to use ModelMapper framework for con

5条回答
  •  佛祖请我去吃肉
    2021-02-02 00:13

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

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

    Service layer code:

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

    Then in your controller, add this:

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

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

    public interface iPost {
       List convertEntityToDTOList();
    }
    

    Credits to @André Carvalho

提交回复
热议问题