您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“JPA @ManyToMany報(bào)錯(cuò)怎么解決”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“JPA @ManyToMany報(bào)錯(cuò)怎么解決”吧!
在使用 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í), 對(duì)應(yīng)的Entity不可使用lombok 的@Data 注解。使用@Setter 、@Getter注解。主要原因是要自己覆寫hash() equals(),toString() 方法。這樣添加和刪除的時(shí)候不會(huì)出現(xiàn)異常。否則出現(xiàn)循環(huán)的引用,不能刪除或stackOver;
不能刪除和添加成功,出現(xiàn)循環(huán)的主要問題在 toString()方法。此方法只能包含基本的元素,不要包含相應(yīng)的@ManyToMany 的對(duì)象 。兩個(gè)類都是。這樣才會(huì)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; }
項(xiàng)目里有一處根據(jù)Id,批量刪除一些歷史數(shù)據(jù)的代碼(xxxRepository.deleteInBatch(list);),發(fā)現(xiàn)傳入list過大時(shí),出現(xiàn)棧溢出(StackOverFlowError) 。
list切分成多份,循環(huán)批量刪除。
下面是簡(jiǎ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 // 最后會(huì)形成 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)用自身,會(huì)不斷的創(chuàng)建棧幀,當(dāng)超出棧深度或者超出棧的大小后,會(huì)爆出 棧溢出。
至于① 處怎么跳出繼續(xù)執(zhí)行后面的代碼,還沒研究,有知道的小伙伴請(qǐng)指教,不正確的地方也請(qǐng)指正。
到此,相信大家對(duì)“JPA @ManyToMany報(bào)錯(cuò)怎么解決”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。