介绍
在本文中,我们将处理 Spring 应用的内部实体与客户端外的 DTO(数据传输对象)之间需要进行的转换。
模型映射
让我们从介绍用于执行的实体到 DTO 转换的主库开始 —— ModelMapper。
我们需要将在 pom.xml 中添加如下依赖:
org.modelmapper
modelmapper
2.3.2
然后,我们在 Spring 配置中定义 ModelMapper bean:
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
DTO
接下来,让我们来介绍这个双面问题的 DTO 方面 —— Post DTO:
public class PostDto {
private static final SimpleDateFormat dateFormat
= new SimpleDateFormat("yyyy-MM-dd HH:mm");
private Long id;
private String title;
private String url;
private String date;
private UserDto user;
public Date getSubmissionDateConverted(String timezone) throws ParseException {
dateFormat.setTimeZone(TimeZone.getTimeZone(timezone));</