2017-12-21 9 views
0

私はSpring MVCフレームワークを使用して簡単なブログWebアプリケーションを作成しています。私はDTOレイヤーを私のアプリケーションに追加したいと思います。ModelMapper、EntitesのリストをDTOオブジェクトのリストにマッピング

私はEntityオブジェクトからDTOオブジェクトを私のビューに変換するためにフレームワークModelMapperを使用することに決めました。

私には1つの問題があります。 私のメインページに、私のブログの投稿のリストを表示しています。私の見解では、それはちょうどPost(エンティティ)オブジェクトのリストです。私はPostDTOオブジェクトのリストを私のビューに渡すように変更したいと思います。 ListPostオブジェクトをListPostDTOオブジェクトに単一のメソッド呼び出しでマップする方法はありますか? 私はこれを変換するconverterを書くことを考えていましたが、それを行うには良い方法だとは思いません。

また、ListsEntitiesは、管理パネルやコメントのようないくつかの場所で、私のページのすべての投稿の下に使用しています。 GitHubのリポジトリに私のアプリのコードに

リンク:repository

答えて

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); 
+0

あなたのコードに基づいて、I似たようなものを書きましたが、わかりやすいものでした。そして、ほとんどの輸入と "私の"。私は 'Java 'の' Generics'には一般的に新しいです。ご助力ありがとうございます。 – Gromo

+0

@Gromo、あなたは歓迎です –

関連する問題