gpt4 book ai didi

java - MapStruct 嵌套列表源以展平目标

转载 作者:行者123 更新时间:2023-12-05 05:54:15 26 4
gpt4 key购买 nike

如何映射以下内容:

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)"' 但在使用表达式时没有空值检查,这可能会导致 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;
}
}

如果你想要可读性,减少检查null的重复代码,你可以使用接口(interface)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;
}
}

关于java - MapStruct 嵌套列表源以展平目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69679607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com