我有以下结构,我想使用 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() 方法不会检查 null 或空文本。
因此,如果我在 DTO 中得到 "comment":null
,则它正在创建一个新的注释对象并将文本设置为 null。
如何避免这种情况?
有人可以解释这种行为并建议我正确的方法吗?
谢谢!
最佳答案
像这样:
@Mapper( componentModel = "spring" )
public interface MyMapper {
@Mapping(source = "entity.comment.text", target = "comment")
DTO toDTO(final ParentEntity entity);
// make sure the entire parameter dto is mapped to comment
@Mapping(source = "dto", target = "comment")
ParentEntity toEntity(final DTO dto);
// and MapStruct will select your own implementation
default CommentEntity dTOToCommentEntity(DTO dTO) {
if ( dTO == null ) {
return null;
}
CommentEntity commentEntity = null;
if ( dTO.getComment()!= null ) {
commentEntity = new CommentEntity();
commentEntity.setText( dTO.getComment() );
}
return commentEntity;
}
}
关于java - Mapstruct 如何将实体映射到字符串以及字符串映射到相应的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57078497/