问题:

JPA 在双向映射时,会相互包含对方的实例,相互引用,造成递归迭代,堆栈溢出(java.lang.StackOverflowError)。

分析:

在后端向前端传递的时候会将数据序列化,转为json,这时会出现循环引用造成堆栈溢出

解决方案:

解决方法就是在转换json时忽略循环字段。首先确定项目使用的json包是哪一个(jackjson 或 fastjson),寻找相应的注解忽略某一字段。

jackson包对应的相关注解: @JsonIgnoreProperties@JsonIgnore

fastjson包对应的相关注解: @JSONField(serialize = false)

注意: 在使用注解时一定要注意引入的包是否正确,如果和自己使用的json包不对应的话,注解是不生效的。

附代码:

// 我的项目使用的alibaba的fastjson包

@Data

class SOStudent {
<span class="token comment"><span class="hljs-comment">// ... ...省略其他字段</span></span>

<span class="token annotation punctuation"><span class="hljs-meta">@ManyToOne</span></span><span class="token punctuation">(</span>cascade <span class="token operator">=</span> <span class="token punctuation">{</span>CascadeType<span class="token punctuation">.</span>REFRESH<span class="token punctuation">}</span><span class="token punctuation">,</span> fetch <span class="token operator">=</span> FetchType<span class="token punctuation">.</span>LAZY<span class="token punctuation">)</span>
<span class="token annotation punctuation"><span class="hljs-meta">@JoinColumn</span></span><span class="token punctuation">(</span>name<span class="token operator">=</span><span class="token string"><span class="hljs-string">"classId"</span></span><span class="token punctuation">)</span>
<span class="token annotation punctuation"><span class="hljs-meta">@JSONField</span></span><span class="token punctuation">(</span>serialize <span class="token operator">=</span> <span class="token boolean"><span class="hljs-keyword">false</span></span><span class="token punctuation">)</span>
<span class="token keyword"><span class="hljs-keyword">private</span></span> SOClass <span class="token keyword"><span class="hljs-class"><span class="hljs-keyword">class</span></span></span><span class="token punctuation">;</span>

}

@Data

class SOClass {

@Id

@GeneratedValue

private Long id

<span class="token comment"><span class="hljs-comment">// ... ...省略其他字段</span></span>

<span class="token annotation punctuation"><span class="hljs-meta">@OneToMany</span></span><span class="token punctuation">(</span>cascade<span class="token operator">=</span><span class="token punctuation">{</span>CascadeType<span class="token punctuation">.</span>ALL<span class="token punctuation">}</span><span class="token punctuation">,</span>fetch <span class="token operator">=</span> FetchType<span class="token punctuation">.</span>EAGER<span class="token punctuation">)</span>
<span class="token keyword"><span class="hljs-keyword">private</span></span> List<span class="token generics function"><span class="token punctuation">&lt;</span>SOStudent<span class="token punctuation">&gt;</span></span> students<span class="token punctuation">;</span>

}

原文地址:https://blog.csdn.net/stoneBridge1920/article/details/87774467

05-11 22:16