JPA @ManyToMany 报错StackOverflowError的解决

网友投稿 266 2022-11-17

JPA @ManyToMany 报错StackOverflowError的解决

目录JPA @ManyToMany 报错StackOverflowErrorSpringJPA批量删除引起的StackOverFlow解决方法

JPA @ManyToMany 报错StackOverflowError

在使用 SpringBoot + JPA 的@ManyToMany 遇到了如下报错

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时, 对应的Entity不可使用lombok 的@Data 注解。使用@Setter 、@Getter注解。主要原因是要自己覆写hash() equals(),toString() 方法。这样添加和删除的时候不会出现异常。否则出现循环的引用,不能删除或stackOver;

不能删除和添加成功,出现循环的主要问题在 toString()方法。此方法只能包含基本的元素,不要包含相应的@ManyToMany 的对象 。两个类都是。这样才会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 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 users;

}

SpringJPA批量删除引起的StackOverFlow

项目里有一处根据Id,批量删除一些历史数据的代码(xxxRepository.deleteInBatch(list);),发现传入list过大时,出现栈溢出(StackOverFlowError) 。

解决方法

list切分成多份,循环批量删除。

下面是简单的了解一下执行流程。

deleteInBatch(Iterable entities)

/**

点进源码 看看。

org.springframework.data.jpa.repository.support.SimpleJpaRepository#deleteInBatch

*/

@Transactional

public void deleteInBatch(Iterable entities) {

Assert.notNull(entities, "The given Iterable of entities not be null!");

if (!entities.iterator().hasNext()) {

return;

}

// 继续跟踪

applyAndBind(getQueryString(DELETE_ALL_QUERY_STRING, entityInformation.getEntityName()), entities, em)

.executeUpdate();

}

/**

org.springframework.data.jpa.repository.query.QueryUtils#applyAndBind

*/

public static Query applyAndBind(String queryString, Iterable 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());

}

}

结合日志记录的错误信息,进入到org.hibernate.hql.internal.antlr.HqlSqlBaseWalker#logicalExpr 方法

下面贴一下调用栈

org.hibernate.hql.internal.antlr.HqlSqlBaseWalker#deleteStatement 方法中 whereClause()调用到了logicalExpr 方法。

由下图可知,该方法在①处递归调用自身,会不断的创建栈帧,当超出栈深度或者超出栈的大小后,会爆出 栈溢出。

至于① 处怎么跳出继续执行后面的代码,还没研究,有知道的小伙伴请指教,不正确的地方也请指正。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:基于TMS320VC5410的实时信号处理系统的设计
下一篇:shell数组详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~