在使用Hibernate进行一对多关联关系映射时,在进行查询时,出现
Infinite recursion (StackOverflowError) (through reference chain
错误信息。
(1)PersonEntity
@Entity( name = "t_person") public class PersonEntity{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @JsonFormat(pattern = "yyyy-MM-dd") private LocalDate birth; @OneToMany @JoinColumn(name = "person_id") private List<AddressEntity> addresses; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public LocalDate getBirth() { return birth; } public void setBirth(LocalDate birth) { this.birth = birth; } public List<AddressEntity> getAddresses() { return addresses; } public void setAddresses(List<AddressEntity> addresses) { this.addresses = addresses; } }
(2)AddressEntity
@Entity( name = "t_address") public class AddressEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String address; private char flag; @ManyToOne private PersonEntity person; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public char getFlag() { return flag; } public void setFlag(char flag) { this.flag = flag; } @JsonIgnore public PersonEntity getPerson() { return person; } @JsonProperty public void setPerson(PersonEntity person) { this.person = person; } }
说明:在getPerson上面增加@JsonIgnore注解即可解决,但是此时在通过JSON方式进行保存时,则无法保存person对象,通过在setPerson上面增加@JsonProperty解决。
{ "address": "中国", "flag": "0", "person": { "id": 2 } }