问题描述
由于响应导致错误,因为“无法编写JSON:无限递归(StackOverflowError)”,我试图直接返回实体,我想以两种形式获取响应而无需转换数据。有人可以解决吗?添加实体结构以供参考。
员工实体
print(df)
index part_1 part_2 first_ix
0 0 4 11 6
1 1 5 12 4
2 2 6 10 4
3 3 4 12 8
4 4 8 14 6
5 5 4 13 8
6 6 6 11 8
7 7 8 10 4
流实体
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long employeeId;
private String firstName;
private String lastName;
private String role;
@OnetoMany(mappedBy = "employee")
private Set<EmployeeStream> streams = new HashSet<>();
}
具有其他属性经验的EmployeeStream实体
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Stream {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long streamId;
private String streamName;
@OnetoMany(mappedBy = "stream")
private Set<EmployeeStream> employees = new HashSet<>();
}
我想以两种形式检索数据
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EmployeeStream {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "EMPLPOYEE_ID")
private Employee employee;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "STREAM_ID")
private Stream stream;
private double experience;
}
{
"employeeId": 1,"firstName": "George","lastName": "Stephen","role": "developer","streams": [
{
"id": 1,"stream": {
"streamId": 1,"streamName": "Java"
},"experience": 1.2
},{
"id": 2,"stream": {
"streamId": 2,"streamName": "Node JS"
},"experience": 2
}
]
}
解决方法
您需要使用下面的代码中的@JsonBackReference
和@JsonManagedReference
。
员工实体
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long employeeId;
private String firstName;
private String lastName;
private String role;
@OneToMany(mappedBy = "employee")
@JsonManagedReference
private Set<EmployeeStream> streams = new HashSet<>();
}
流实体
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Stream {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long streamId;
private String streamName;
@OneToMany(mappedBy = "stream")
@JsonManagedReference
private Set<EmployeeStream> employees = new HashSet<>();
}
EmployeeStream实体
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EmployeeStream {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "EMPLPOYEE_ID")
@JsonBackReference
private Employee employee;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "STREAM_ID")
@JsonBackReference
private Stream stream;
private double experience;
}
更新:以前@JsonBackReference
和@JsonManagedReference
的位置不正确,更正了相同的地方。
注意:如果仍然遇到任何问题,请尝试从@JsonManagedReference
和Stream
实体中删除Employee
。