JPA?@ManyToMany?報(bào)錯(cuò)StackOverflowError的解決
JPA @ManyToMany 報(bào)錯(cuò)StackOverflowError
在使用 SpringBoot + JPA 的@ManyToMany 遇到了如下報(bào)錯(cuò)
java.lang.StackOverflowError: null
2021-02-07 10:59:59.490 ERROR 100440 --- [io-20012-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet]:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed;
nested exception is 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:
com.xxx.entity.boem.EquipmentManage["dataPublishes"]->org.hibernate.collection.internal.PersistentSet[0]
->com.xxx.entity.bods.DataPublish["equipmentManages"]->org.hibernate.collection.internal.PersistentBag[0]
->com.xxx.entity.boem.EquipmentManage["dataPublishes"]->org.hibernate.collection.internal.PersistentSet[0]
->com.xxx.entity.bods.DataPublish["equipmentManages"]->org.hibernate.collection.internal.PersistentBag[0]
->com.xxx.entity.boem.EquipmentManage["dataPublishes"]->org.hibernate.collection.internal.PersistentSet[0]
->.......
..........
注意:
使用@ManyToMany時(shí), 對應(yīng)的Entity不可使用lombok 的@Data 注解。使用@Setter 、@Getter注解。主要原因是要自己覆寫hash() equals(),toString() 方法。這樣添加和刪除的時(shí)候不會出現(xiàn)異常。否則出現(xiàn)循環(huán)的引用,不能刪除或stackOver;
不能刪除和添加成功,出現(xiàn)循環(huán)的主要問題在 toString()方法。此方法只能包含基本的元素,不要包含相應(yīng)的@ManyToMany 的對象 。兩個(gè)類都是。這樣才會ok.
@Setter @Getter @Entity public class User { @Id @GenericGenerator(name="jpauuid",strategy = "org.hibernate.id.UUIDGenerator") @GeneratedValue(generator = "jpauuid") @Column(length = 32,nullable = false) private String id; @Column(length = 30) private String username; @ManyToMany(cascade = CascadeType.REFRESH,mappedBy = "users") private Set<Role> roles; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return id.equals(user.id) && username.equals(user.username) && roles.equals(user.roles); } @Override public int hashCode() { return Objects.hash(id, username, roles); } @Override public String toString() { return "User{" + "id='" + id + '\'' + ", username='" + username + '\'' + ", roles=" + roles + '}'; } }
@Setter @Getter @Entity public class Role { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(length = 30) private String name; @ManyToMany(cascade = CascadeType.REFRESH) @JoinTable(name = "user_role",joinColumns = @JoinColumn(name = "role_id"),inverseJoinColumns = @JoinColumn(name="user_id")) private Set<User> users; }
SpringJPA批量刪除引起的StackOverFlow
項(xiàng)目里有一處根據(jù)Id,批量刪除一些歷史數(shù)據(jù)的代碼(xxxRepository.deleteInBatch(list);),發(fā)現(xiàn)傳入list過大時(shí),出現(xiàn)棧溢出(StackOverFlowError) 。
解決方法
list切分成多份,循環(huán)批量刪除。
下面是簡單的了解一下執(zhí)行流程。
deleteInBatch(Iterable<T> entities) /** 點(diǎn)進(jìn)源碼 看看。 org.springframework.data.jpa.repository.support.SimpleJpaRepository#deleteInBatch */ @Transactional public void deleteInBatch(Iterable<T> entities) { Assert.notNull(entities, "The given Iterable of entities not be null!"); if (!entities.iterator().hasNext()) { return; } // 繼續(xù)跟蹤 applyAndBind(getQueryString(DELETE_ALL_QUERY_STRING, entityInformation.getEntityName()), entities, em) .executeUpdate(); } /** org.springframework.data.jpa.repository.query.QueryUtils#applyAndBind */ public static <T> Query applyAndBind(String queryString, Iterable<T> entities, EntityManager entityManager) { // ... 省略一些code // 最后會形成 delete from xx表 x(表別名) where x.id =? or x.id=?... 一條sql語句 String alias = detectAlias(queryString); StringBuilder builder = new StringBuilder(queryString); builder.append(" where"); int i = 0; while (iterator.hasNext()) { iterator.next(); builder.append(String.format(" %s = ?%d", alias, ++i)); if (iterator.hasNext()) { builder.append(" or"); } } Query query = entityManager.createQuery(builder.toString()); iterator = entities.iterator(); i = 0; while (iterator.hasNext()) { query.setParameter(++i, iterator.next()); } }
結(jié)合日志記錄的錯(cuò)誤信息,進(jìn)入到org.hibernate.hql.internal.antlr.HqlSqlBaseWalker#logicalExpr 方法
下面貼一下調(diào)用棧
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker#deleteStatement 方法中 whereClause()調(diào)用到了logicalExpr 方法。
由下圖可知,該方法在①處遞歸調(diào)用自身,會不斷的創(chuàng)建棧幀,當(dāng)超出棧深度或者超出棧的大小后,會爆出 棧溢出。
至于① 處怎么跳出繼續(xù)執(zhí)行后面的代碼,還沒研究,有知道的小伙伴請指教,不正確的地方也請指正。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring?createBeanInstance實(shí)例化Bean
這篇文章主要為大家介紹了Spring?createBeanInstance實(shí)例化Bean源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03java異常處理機(jī)制示例(java拋出異常、捕獲、斷言)
這篇文章主要介紹了java異常處理機(jī)制示例(java拋出異常、捕獲、斷言),需要的朋友可以參考下2014-05-05web項(xiàng)目WEB-INF下沒有web.xml的解決方法
新手如果在web項(xiàng)目創(chuàng)建后WEB-INF下面沒有出現(xiàn)web.xml,怎么辦?別慌,沒有web.xml文件的原因是因?yàn)樵趧?chuàng)建web項(xiàng)目的時(shí)候沒有把創(chuàng)建web.xml勾上。這篇文章主要介紹了web項(xiàng)目WEB-INF下沒有web.xml的解決方法,需要的朋友可以參考下2022-12-12Spring?boot?Thymeleaf配置國際化頁面詳解
這篇文章主要給大家介紹了關(guān)于Spring?Boot?Thymeleaf實(shí)現(xiàn)國際化的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Spring?Boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07Springboot+SpringSecurity實(shí)現(xiàn)圖片驗(yàn)證碼登錄的示例
本文主要介紹了Springboot+SpringSecurity實(shí)現(xiàn)圖片驗(yàn)證碼登錄的示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04SpringBoot整合sharding-jdbc實(shí)現(xiàn)分庫分表與讀寫分離的示例
本文主要介紹了SpringBoot整合sharding-jdbc實(shí)現(xiàn)分庫分表與讀寫分離的示例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11Required?request?body?is?missing的問題及解決
這篇文章主要介紹了Required?request?body?is?missing的問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12