我试图实现 MapStruct 映射库。我已经制作了示例,对于简单的映射,它工作正常,但我陷入了 1 个问题。 我有 2 个 jpa 实体类,它们具有两种方式的关系。一个存在于另一个之中,另一个又存在于一个之中。它会产生循环映射问题,因此 MapStruct 会引发 StackOverflow 错误。 我创建了最少的代码来重现 github 上的案例。 示例代码:
public class A {
private Long id;
private String name;
private B bData;
//getter-setter
}
public class B {
private Long id;
private String name;
private Set<A> aData;
//getter-setter
}
数据生成器
public class DataGenerator {
public static A generateData(){
A a = new A();
a.setId(1L);
a.setName("foo");
B b = new B();
b.setId(2L);
b.setName("bar");
A a2 = new A();
a2.setId(3L);
a2.setName("john");
a2.setbData(b);
A a3 = new A();
a3.setId(4L);
a3.setName("doe");
a3.setbData(b);
Set<A> aData = new HashSet<A>();
aData.add(a2);
aData.add(a3);
b.setaData(aData);
a.setbData(b);
return a;
}
}
映射器
@Mapper
public interface CustomMapper {
CustomMapper INSTANCE = Mappers.getMapper(CustomMapper.class);
ADto atoADto(A a);
}
应用程序
public class AppMain {
public static void main(String[] args) {
A a = DataGenerator.generateData();
ADto aDto = CustomMapper.INSTANCE.atoADto(a);
System.out.println(aDto.getId());
}
}
Dto/Destination 类与原始源类相同。 主要是循环/递归映射问题导致堆栈溢出错误。
使用spring BeanUtils.copyProperties有同样的效果,但我想实现MapStruct。目前我正在考虑用 MapStruct 替换 spring BeanUtils。
有什么建议吗?
最佳答案
查看此mapstruct github issue解决方案是忽略导致递归的字段。我引用:
“您可以使用@Qualifier来实现它。您可以使用@Named和qualifiedByName,或者您可以使用您自己的自定义@CountryWithoutCities限定符和qualifiedBy。
Class country{
String id;
String name;
List<City> cities;
}
Class City{
String id;
String name;
Country country;
}
@Mapper(uses = CityMapper.class)
interface CountryMapper {
@Mapping( target = "cities", qualifiedByName = "noCountry")
CountryDto toDto(Country country);
@CountryWithoutCities
@Mapping( target = "cities", ignore = true)
CountryDto toDtoWithoutCities(Country country);
}
@Mapper(uses = CountryMapper.class)
interface CityMapper {
@Named( "noCountry" )
@Mapping( target = "country", ignore = true)
CityDto toDtoWithoutCountry(City city);
@Mapping( target = "country", qualifiedBy= CountryWithoutCities.class)
CityDto toDto(City city);
}
关于java - 递归映射时的 MapStruct 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58776970/