如何修复弹簧靴一对多双向无限循环?
作者:互联网
我尝试使用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);
}
}
它看起来像是内斗循环,并且我的服务器抛出错误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"}
]
它没有向我显示雇主的详细信息.
请向我建议我在做什么错.提前致谢!!
解决方法:
使用JSON,则是双向映射的问题.使用以下属性.
@JsonIgnoreProperties("employer")
@JsonIgnoreProperties("employees")
请保持获取类型的热情.
希望这会起作用.
标签:spring,spring-boot,spring-data,hibernate-mapping,bidirectional 来源: https://codeday.me/bug/20191013/1906207.html