【发布时间】:2019-12-27 11:39:52
【问题描述】:
我最近开始在一个项目中使用 MapStruct 映射工具。过去,为了映射 DTO -> 实体,反之亦然,我使用自定义映射器,例如:
public static CustomerDto toDto(Customer customer) {
return isNull(customer)
? null
: CustomerDto.builder()
.id(customer.getId())
.name(customer.getName())
.surname(customer.getSurname())
.phoneNumber(customer.getPhoneNumber())
.email(customer.getEmail())
.customerStatus(customer.getCustomerStatus())
.username(customer.getUsername())
.NIP(customer.getNIP())
.build();
}
如果我试图获得一个 Optional 对象,毕竟我能够通过以下方式将我的实体映射到 dto:
public Optional<CustomerDto> findOneById(final long id) {
return customerRepository.findById(id).map(CustomerMapper::toDto);
}
目前,正如我之前提到的,我正在使用 mapStruct,问题是我的映射器不是类,它的接口如下:
@Mapper
public interface CommentMapper {
@Mappings({
@Mapping(target = "content", source = "entity.content"),
@Mapping(target = "user", source = "entity.user")
})
CommentDto commentToCommentDto(Comment entity);
@Mappings({
@Mapping(target = "content", source = "dto.content"),
@Mapping(target = "user", source = "dto.user")
})
Comment commentDtoToComment(CommentDto dto);
}
我想知道是否有可能以某种方式在流温柔中使用此接口方法来映射我的值,而无需包装如下值:
public Optional<CommentDto> findCommentById(final long id) {
Optional<Comment> commentById = commentRepository.findById(id);
return Optional.ofNullable(commentMapper.commentToCommentDto(commentById.get()));
}
感谢您的帮助。
【问题讨论】:
-
可选 = 一个容器对象,它可能包含也可能不包含非空值。如果没有注释,请不要将其作为“findById”方法的结果返回,只需返回 null!评论评论 = commentRepository.findById(id).orElse(null);
-
MapStructs 就像 lombok 一个经过预处理的接口,它正在生成一个 Impl 类。