【发布时间】:2023-03-10 14:19:01
【问题描述】:
我有以下结构,我想使用 mapstruct 映射它。
class DTO
{
private Integer id;
String comment;
//getters & setters
}
class ParentEntity
{
private Integer id;
CommentEntity comment;
//getters & setters
}
class CommentEntity
{
private Integer id;
private String text;
//getters & setters
}
@Mapper(componentModel = "spring")
public interface SampleMapper
{
@Mapping(source = "entity.comment.text", target = "comment")
public DTO toDTO(final ParentEntity entity);
@Mapping(source = "dto.comment", target = "comment.text")
public ParentEntity toEntity(final DTO dto);
}
下面是mapstruct为toDTO方法生成的实现
@Override
public DTO toDTO(ParentEntity entity) {
if ( entity == null ) {
return null;
}
DTO dto = new DTO();
dto.setComment( entityCommentText( entity ) );
....................
}
private String entityCommentText(ParentEntity entity) {
if ( entity == null ) {
return null;
}
Comment comment = entity.getComment();
if ( comment == null ) {
return null;
}
String text = comment.getText();
if ( text == null ) {
return null;
}
return text;
}
下面是mapstruct为toEntity方法生成的实现
@Override
public ParentEntity toEntity(DTO dto) {
if ( dto == null ) {
return null;
}
ParentEntity entity = new ParentEntity();
entity.setComment( dtoToCommentEntity( dto ) );
.............
}
protected CommentEntity dtoToCommentEntity(DTO dto) {
if ( dto == null ) {
return null;
}
CommentEntity commentEntity = new CommentEntity();
commentEntity.setText( dto.getComment() );
return commentEntity;
}
我的问题是toDTO() 方法仅在文本不为空时才设置注释。但toEntity() 方法不检查空文本或空文本。
因此,如果我在 DTO 中得到 "comment":null,它正在创建一个新的评论对象并将文本设置为空。
如何避免这种情况?
有人可以解释这种行为并建议我正确的方法吗?
谢谢!
【问题讨论】:
-
试试这个
@Mapper(componentModel = "spring", nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS) -
我认为这会破坏很多其他的东西。
-
对于原始类型,可以按原样复制空值。但是有一个文本为 null 的评论对象是没有意义的。