gpt4 book ai didi

spring - 如何修复 Spring Boot 一对多双向无限循环?

转载 作者:行者123 更新时间:2023-12-02 05:47:44 24 4
gpt4 key购买 nike

我尝试使用 spring boot 和 spring data jpa 创建一对多双向映射,请查看下面的实体

Employer Entity

@Entity  
public class Employer
{
private Long id;
private String employerName;
private List<Employee> employees;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getEmployerName()
{
return employerName;
}
public void setEmployerName(String employerName)
{
this.employerName = employerName;
}

@OneToMany(cascade=CascadeType.ALL, mappedBy="employer")
public List<Employee> getEmployees()
{
return employees;
}
public void setEmployees(List<Employee> employees)
{
this.employees = employees;
}
}

Employee Entity

@Entity  
public class Employee
{
private Long id;
private String employeeName;
private Employer employer;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getEmployeeName()
{
return employeeName;
}
public void setEmployeeName(String employeeName)
{
this.employeeName = employeeName;
}
@ManyToOne(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
public Employer getEmployer()
{
return employer;
}
public void setEmployer(Employer employer)
{
this.employer = employer;
}
}

Employer Repo

public interface EmployerServices extends JpaRepository<Employer, Long> {
}

Employee Repo

public interface EmployeeServices extends JpaRepository<Employee, Long> {
}

REST Controller is

 @RestController
public class Controller {
@Autowired EmployeeServices employeeServices;
@Autowired EmployerServices employerServices;
@GetMapping("/getempr")
public Object getempr(){
return employerServices.findOne(1L);
}
}

现在问题开始了,看看我的输出 enter image description here

它看起来像一个内讧循环,并且我的服务器抛出错误 getOutputStream() 已经被调用用于此响应。

 I used @JsonBackReference & @JsonManagedReference 

注释,但问题是它的工作方式像一对多

 {
"id":1,
"employerName":"employer",
"employees":[
{"id":1,"employeeName":"emp1"},
{"id":2,"employeeName":"emp2"}
]
}

如果我想引起多对一的关注,就像所有雇员与雇主一样。输出是

 [
{
"id":1,
"employeeName":"emp1"
},
{
"id":2,
"employeeName":"emp2"}
]

它没有向我显示雇主详细信息。

请告诉我我做错了什么。提前致谢!!

最佳答案

不要使用@JsonBackReference@JsonManagedReference,而是尝试使用注释@JsonIgnoreProperties:

@JsonIgnoreProperties("employer")
private List<Employee> employees;

@JsonIgnoreProperties("employees")
private Employer employer;

它阻止 Jackson 渲染关联对象的指定属性。

关于spring - 如何修复 Spring Boot 一对多双向无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49130173/

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