springboot整合jpa踩過的坑(二)
一、org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion(StackOverflowError);nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain:xxxxxx
從異常中資訊能夠看出在轉化為json的過程中產生了死迴圈,把A類轉化為json的時候,A類中做了B類的關聯對映,而B類中又管理了A類,這樣就產生了json轉化死迴圈,究其原因是因為在雙向關聯的時候沒有指定哪一方來維護關聯關係,所以才會產生這樣的原因,有兩種解決方法:
①在一方的的get方法中加上@JsonBackReference註解
②指定維護關係,
(1)可以在 one 方指定 @OneToMany 註釋並設定 mappedBy 屬性,以指定它是這一關聯中的被維護端,many 為維護端。
例:@OneToMany(fetch = FetchType.LAZY ,targetEntity = DeviceEntity.class,mappedBy = "areaId")
(2)在雙向的一對一關聯中,需要在關係被維護端(inverse side)中的 @OneToOne 註釋中指定 mappedBy,以指定是這一關聯中的被維護端
TemplateEntity.java
@OneToOne(fetch = FetchType.LAZY ,cascade = CascadeType.ALL, mappedBy = "templateEntity")
public ConfigEntity getConfigEntity() {
return configEntity;
}
ConfigEntity.java
@JoinColumn(name = "template_id" , insertable = false , updatable = false)
public TemplateEntity getTemplateEntity() {
return templateEntity;
}
(mappedBy屬性定義了此類為雙向關係的維護端,注意:mappedBy 屬性的值為此關係的另一端的屬性名。)
二、org.hibernate.MappingException: Could not determine type for: xxxxxx
這是因為在實體類中建立關聯關係的時候,要把關聯關係註解加在getter方法,在屬性或setter方法上就會出現這樣情況