在将spring-boot与JPA存储库集成时出现这些错误
这是代码
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api")
public class EmpController {
@Autowired
private CrudRepo crud;
@Autowired
private AddrCrudRepo addr;
@Autowired
private EntityManager entity;
//@Autowired
//private ModelMapper mapper;
private static int count = 0;
@Bean
public ModelMapper model() {
return new ModelMapper();
}
//@Autowired
// public EmpController(ModelMapper mapper) {
// this.mapper = mapper;
// }
@RequestMapping(path = "/post-addr", method = RequestMethod.POST)
public List<AddressModel> postAddr(@Valid @RequestBody List<AddressRequest> addr1){
// crud.findById(id)
//AddressModel list = new AddressModel();
EmployeeModel emp = new EmployeeModel();
System.out.println("CALLING THE MAPPER "+addr1);
List<AddressModel> addr_list = ObjectMapperUtils.mapAll(addr1, AddressModel.class);
System.out.println("CALLED THE MAPPER "+addr_list);
addr_list.forEach((a) -> {
crud.findById(a.getEmpId()).ifPresent((b) -> {
System.out.println(this.count++);
a.setEmp_id(b);
b.getAddress().add(a);
});
});
// AddressModel addr_list = model().map(addr1, AddressModel.class);
//
// crud.findById(addr1.getEmp_id()).ifPresent((b) -> {
// addr_list.setEmp_id(b);
//
// });`enter code here`
System.out.println(addr_list.size());
List<AddressModel> addr3 = addr.saveAll(addr_list);
System.out.println(addr3);
return addr_list;
}
当
postAddr
方法返回List<AddressModel>
时出现错误,这是AddressModel
@Entity
@Table(name="Emp_Address")
public class AddressModel implements Serializable{
@Column(name="address_id")
@Id
private Integer address_id;
@Column(name="city")
private String city;
@Column(name="states")
private String states;
@Transient
private Integer empId;
@ManyToOne
@JoinColumn(name="emp_id")
private EmployeeModel emp_id;
public AddressModel() {
}
//getter and setter
和
EmployeeModel
@Entity
@Table(name="Employee")
public class EmployeeModel implements Serializable{
@Column(name="Emp_id")
@Id
private Integer emp_id;
@Column(name="Emp_Name")
private String emp_name;
@OneToMany(mappedBy="emp_id")
private Collection<AddressModel> address = new ArrayList<>();
public EmployeeModel() {
}
//getter and setters
因此尽管saveAll正确完成,但是当postAddr方法返回List时,它将引发StackOverflow
最佳答案
之所以会出现此StackOverflow
错误,是因为这两个类的生成的toString
方法彼此循环依赖。EmployeeModel
尝试打印AddressModel
,但是AddressModel
再次尝试打印EmployeeModel
,因此错误。
尝试从AddressModel
类的toString
方法中删除EmployeeModel
,或者相反,从EmployeeModel
类的toString
方法中删除AddressModel
。