亲宝软件园·资讯

展开

JPA @ManyToMany报错StackOverflowError

浩骞 人气:0

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<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

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

解决方法

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

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

 deleteInBatch(Iterable<T> entities) 
/**
  点进源码 看看。
  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;
		} 
// 继续跟踪
		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());
		}  
}

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

下面贴一下调用栈

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

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

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论