如何映射以下内容:
class Source {
String name;
List<Other> others;
}
class Other {
String otherName;
List<More> mores;
}
class More {
String moreName;
}
class Target {
String name;
String otherName;
String moreName;
}
希望是这样的:
@Mapper
public interface MyMapper {
@Mapping(target = "name", source = "name")
@Mapping(target = "otherName", source = "others[0].otherName")
@Mapping(target = "morename", source = "others[0].mores[0].moreName")
Target map(Source source);
我看到'expression = "java(others.get(0). othername)"'可以使用,但是在使用expression时没有null检查,这可能导致NullPointeException。有什么建议与空检查和默认可以应用吗?
您可以使用expression
检查空值并返回一些内容
@Mapper
public interface MyMapper {
@Mapping(target = "name", source = "name")
@Mapping(target = "otherName", expression = "java(s.others != null && !s.others.isEmpty() ? s.others.get(0).otherName : "")")
@Mapping(target = "moreName", expression = "java(s.others != null && !s.others.isEmpty() && s.others.get(0).mores != null && !s.others.get(0).mores.isEmpty() ? s.others.get(0).mores.get(0).moreName : "")")
Target map(Source s);
}
// mapstruct code generate.
public class MyMapperImpl implements MyMapper {
@Override
public Target map(Source s) {
if ( s == null ) {
return null;
}
Target target = new Target();
target.name = s.name;
target.otherName = s.others != null && !s.others.isEmpty() ? s.others.get(0).otherName : "";
target.moreName = s.others != null && !s.others.isEmpty() && s.others.get(0).mores != null && !s.others.get(0).mores.isEmpty() ? s.others.get(0).mores.get(0).moreName : "";
return target;
}
}
如果您希望可读并减少检查空重复代码,您可以使用接口default
方法并使用org.springframework.util.ObjectUtils.isEmpty()
。
@Mapper
public interface MyMapper {
@Mapping(target = "name", source = "name")
@Mapping(target = "otherName", expression = "java(getFirstOtherName(s))")
@Mapping(target = "moreName", expression = "java(getFirstMoreName(s))")
Target map(Source s);
default String getFirstOtherName(Source s) {
return !ObjectUtils.isEmpty(s.others) ? s.others.get(0).otherName : "";
}
default String getFirstMoreName(Source s) {
return !ObjectUtils.isEmpty(s.others) && !ObjectUtils.isEmpty(s.others.get(0).mores) ? s.others.get(0).mores.get(0).moreName : "";
}
}
// mapstruct code generate.
public class MyMapperImpl implements MyMapper {
@Override
public Target map(Source s) {
if ( s == null ) {
return null;
}
Target target = new Target();
target.name = s.name;
target.otherName = getFirstOtherName(s);
target.moreName = getFirstMoreName(s);
return target;
}
}
我想你需要看看这个例子:MapStruct字符串到列表映射
基本上,您需要在获取一些元素之前验证列表的大小。