2017-12-21 1 views
0

Spring MVC 프레임 워크를 사용하여 간단한 블로그 웹 응용 프로그램을 작성하고 있습니다. 내 앱에 DTO 레이어를 추가 할 용의가 있습니다.ModelMapper, Entites 목록을 DTO 객체 목록으로 매핑

Entity 개체에서 내보기에 사용 된 개체 인 DTO 개체로 변환하기 위해 ModelMapper 프레임 워크를 사용하기로 결정했습니다.

하나의 문제가 있습니다. 내 메인 페이지에서 내 블로그에 게시물 목록을 표시하고 있습니다. 내보기에는 단지 Post (Entity) 개체 목록 일뿐입니다. 내보기에 PostDTO 개체 목록을 전달하도록 변경하고 싶습니다. 어떤 방법으로도 ListPost 개체를 ListPostDTO 개체로 단일 메서드 호출로 매핑 할 수 있습니까? 나는 이것을 변환 할 converter을 쓰려고 생각하고 있었지만, 좋은 방법이라고 확신하지는 못했다.

또한 ListsEntities을 내 페이지의 모든 게시물 아래 관리 패널이나 댓글과 같은 몇 가지 장소에서 사용하고 있습니다. GitHub의 저장소에 내 응용 프로그램의 코드

링크 : repository

답변

1
당신은 폴더의 유틸리티 클래스를 만들 수 있습니다

:

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; 
    } 
} 

을 그리고 당신의 필요를 위해 그것을 사용 : 코드의 I에

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

을 바탕으로 비슷한 것을 썼지 만 나를 이해하기 쉽다. 그리고 대부분의 수입과 "광산". 나는'Java'에서'Generics'를 처음 접했습니다. 당신의 도움을 주셔서 대단히 감사합니다. – Gromo

+0

@ 그로 모, 천만에요. –

관련 문제