@JsonIgnore 直接忽略循环引用字段,简单但可能导致数据丢失。 public class User { @OneToMany(mappedBy = "user") @JsonIgnore // 序列化时忽略orders字段 private List<Order> orders; }
@JsonManagedReference / @JsonBackReference 定义父子关系,仅序列化前向引用(适合双向关联)。 public class User { @OneToMany(mappedBy = "user") @JsonManagedReference // 前向引用保留 private List<Order> orders; } public class Order { @ManyToOne @JsonBackReference // 反向引用忽略 private User user; }
@JsonIdentityInfo 为对象生成唯一ID,重复引用时用ID替代(适合复杂对象图)。 @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class User { private Long id; private List<Order> orders; }
2. 数据模型重构
DTO(Data Transfer Object)模式 创建扁平化数据传输对象,切断循环引用链。 public class UserDTO { private Long id; private List<Long> orderIds; // 仅存储关联ID }
引入中间表 通过ID关联代替对象嵌套,例如订单表增加userId字段。
3. 序列化配置调整
Jackson全局配置 禁用循环引用检测(慎用,可能引发栈溢出)。 ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, false);