mapstruct 用于实体间的转换
2018-04-05 本文已影响0人
mibro
代码样例
@Mapper(componentModel = "spring")
public interface SellerReviewDTOConverter {
@Mappings({
@Mapping(source = "reviewRateId", target = "id"),
@Mapping(source = "reviewContent", target = "detail"),
@Mapping(source = "zonedReviewTime", target = "createdAt", dateFormat = "yyyy-MM-dd HH:mm:ss"),
@Mapping(source = "reviewStatus", target = "status"),
@Mapping(source = "realBuyerName", target = "customerName"),
@Mapping(source = "buyerId", target = "customerId"),
@Mapping(source = "tradeOrderId", target = "orderId"),
@Mapping(source = "zonedBoughtDate", target = "orderTime", dateFormat = "yyyy-MM-dd HH:mm:ss"),
@Mapping(source = "qcTag", target = "tag"),
@Mapping(source = "rejectionReason", target = "rejectionReason")
})
SellerReviewResponseDTO dto2domain(SellerReviewDTO o);
}
编译结果
@Component
public class SellerReviewCsvDTOConverterImpl implements SellerReviewCsvDTOConverter {
public SellerReviewCsvDTOConverterImpl() {
}
public SellerReviewCsvDTO dto2domain(SellerReviewDTO o) {
if (o == null) {
return null;
} else {
SellerReviewCsvDTO sellerReviewCsvDTO = new SellerReviewCsvDTO();
if (o.getZonedReviewTime() != null) {
sellerReviewCsvDTO.setCreatedAt(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(o.getZonedReviewTime()));
}
if (o.getTradeOrderId() != null) {
sellerReviewCsvDTO.setOrderId(String.valueOf(o.getTradeOrderId()));
}
sellerReviewCsvDTO.setCustomerEmail(o.getBuyerEmail());
sellerReviewCsvDTO.setSellerName(o.getSellerName());
sellerReviewCsvDTO.setRating(o.getRating());
sellerReviewCsvDTO.setClient(o.getClientType());
sellerReviewCsvDTO.setReviewOrigin(o.getSource());
sellerReviewCsvDTO.setDetail(o.getReviewContent());
sellerReviewCsvDTO.setRejectionReason(o.getRejectionReason());
sellerReviewCsvDTO.setCustomerName(o.getRealBuyerName());
sellerReviewCsvDTO.setStatus(o.getReviewStatus());
return sellerReviewCsvDTO;
}
}
}
@Mapper 注解的 componentModel 属性
用于指定自动生成的接口实现类的组件类型,这个属性支持四个值:
- default: 这是默认的情况,mapstruct 不使用任何组件类型, 可以通过Mappers.getMapper(Class)方式获取自动生成的实例对象。
- cdi: the generated mapper is an application-scoped CDI bean and can be retrieved via @Inject
- spring: 生成的实现类上面会自动添加一个@Component注解,可以通过Spring的 @Autowired方式进行注入
- jsr330: 生成的实现类上会添加@javax.inject.Named 和@Singleton注解,可以通过 @Inject注解获取