【Hibernate】Hibrenate POJO 类在序列化时遇到的问题
生活随笔
收集整理的這篇文章主要介紹了
【Hibernate】Hibrenate POJO 类在序列化时遇到的问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
假設某 POJO 有屬性如下:
private Set<User> users = new HashSet<>(0);@OneToMany(fetch = FetchType.LAZY, mappedBy = "xuser")public Set<User> getUsers() {return this.users; }如果我們使用jackson將其序列化,運行時會報錯,myeclipse對宕機:
failed to lazily initialize a collection of role ...解決方法一: 通過 Hibernate 的 OpenSessionInViewFilter 使得 FetchType 為 LAZY 的屬性在序列化時為空,在 web.xml 中添加代碼如下:
<filter> <filter-name>openSession</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>false</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSession</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>盡管 users 為空,但字段依然保留,對應輸出:
{...,"users":[],...}解決方法二:
在屬性的 get 方法之前加上注解 @JsonIgnore,如此在轉換為 JSON 時該字段被忽略:
import com.fasterxml.jackson.annotation.JsonIgnore; … private Set<User> users = new HashSet<>(0); @JsonIgnore @OneToMany(fetch = FetchType.LAZY, mappedBy = "xuser")public Set<User> getUsers() {return this.users; } …注意引入的類是 com.fasterxml.jackson.annotation.JsonIgnore,如果使用 org.codehaus.jackson.annotate.JsonIgnore 則不能生效,見 Spring @JsonIgnore not working 。
解決方法三:
fetch = FetchType.LAZY 改為 fetch = FetchType.EAGER,但這樣會導致每次查詢數據庫都要立即提取 OneToMany 的所有對象,所以非常不推薦。
轉載于:https://my.oschina.net/whitejavadog/blog/877286
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的【Hibernate】Hibrenate POJO 类在序列化时遇到的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Uva 11732 strcmp()函数
- 下一篇: varnish---反向代理web加速缓