我正在使用Spring MVC框架编写简单的博客Web应用程序。我愿意DTO在我的应用程序中添加图层。
我决定使用ModelMapper框架从Entity对象转换为DTO视图中使用的对象。
我只有一个问题。在我的主页上,我正在显示博客中的帖子列表。在我看来,这只是Post(实体)对象的列表。我想更改它以将PostDTO对象列表传递给我的视图。有没有什么办法来映射List的Post对象List的PostDTO单方法调用的对象?我当时正在考虑编写将转换该转换器的转换器,但是我不确定这是否是一个好方法。
另外,我还在其他几个地方使用Lists,Entities例如管理面板或页面上每个帖子下方的评论。
And*_*oda 14
您可以创建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;
}
}
Run Code Online (Sandbox Code Playgroud)
并将其用于您的需求:
List<PostDTO> listOfPostDTO = ObjectMapperUtils.mapAll(listOfPosts, PostDTO.class);
Run Code Online (Sandbox Code Playgroud)
小智 13
考虑到您拥有Post Entity(postEntityList)和PostDTO类的列表,可以尝试以下操作:
使用以下导入获取所需的结果
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import java.lang.reflect.Type;
Run Code Online (Sandbox Code Playgroud)
使用下面的代码
Type listType = new TypeToken<List<PostDTO>>(){}.getType();
List<PostDTO> postDtoList = modelmapper.map(postEntityList,listType);
Run Code Online (Sandbox Code Playgroud)
小智 10
既然你想把Entity转Dto,你可以试试下面的
List<PostDTO> entityToDto = modelMapper.map(postEntity, new TypeToken<List<PostDTO>>(){}.getType());
Run Code Online (Sandbox Code Playgroud)
试试下面的简单方法:
List<PostDTO> postDtoList = Arrays.asList(modelMapper.map(postEntityList, PostDTO[].class));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16799 次 |
| 最近记录: |