对象拷贝作用于JPA中的实体时,可能会出现两个实体循环依赖的问题,导致序列化失败。原则上不建议在DTO层面定义循环依赖的关系,如果因为特殊原因无法避免,框架会自动将循环依赖的字段设置为null
。
class Foo {
String name = "foo";
@OneToMany
List<Bar> bars;
}
class Bar {
String name = "bar";
@ManyToOne
Foo foo;
}
class FooDto {
String name;
List<Bar> bars;
}
Foo foo = fooRepository.findById(1L);
FooDto fooDto = BeanUtils.copyProperties(foo, FooDto.class);
System.out.println(foo); // StackOverflowError
System.out.println(fooDto);
/**
* {
* "name": "foo",
* "bars": [
* {
* "name": "bar",
* "foo": null
* },
* ...
* ]
* }
*/