大佬教程收集整理的这篇文章主要介绍了Spring Boot JPA-OneToMany关系导致无限循环,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
问题解决了。我@toString
在linkedAccount中使用自定义方法,该方法引用了ParentAccount。我不知道这会导致任何问题,因此我没有在问题中包含toString。
显然,这导致了延迟加载的无限循环,删除此引用可解决此问题。
我有两个具有简单@OneToMany关系的对象,其外观如下:
父母:
@Entity
public class ParentAccount {
@Id
@GeneratedValue
private long id;
private String name;
@OneToMany(fetch = FetchType.EAGER,mappedBy = "parentAccount")
private Set<LinkedAccount> linkedAccounts;
}
儿童:
@Entity
public class LinkedAccount {
@Id
@GeneratedValue
private long id;
@manyToOne(optional = falsE)
private ParentAccount parentAccount;
private String name;
// empty constructor for JPA
public LinkedAccount() {
}
}
我可能使用Spring CrudRepository
来处理这些实体。但是,在调用时ParentAccount parent =
parentAccountRepository.findOne(id);
,会开始发生某种无限循环,并在整个控制台中将其变为垃圾邮件hibernate状态:
Hibernate: SELEct linkedacco0_.parent_account_id as parent_a6_1_0_,linkedacco0_.id as id1_0_0_,linkedacco0_.id as id1_0_1_,linkedacco0_.aws_id as aws_id2_0_1_,linkedacco0_.key_id as key_id3_0_1_,linkedacco0_.name as name4_0_1_,linkedacco0_.parent_account_id as parent_a6_0_1_,linkedacco0_.secret_key as secret_k5_0_1_ from linked_account linkedacco0_ where linkedacco0_.parent_account_id=?
我尝试将获取类型更改为LAZY,但随后出现此错误:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.berrycloud.scheduler.model.ParentAccount.linkedAccounts,could not initialize proxy - no Session
(似乎它正在尝试在事务上下文之外进行延迟加载)。
这是我的CRUD存储库:
@Repository
public interface ParentAccountRepository extends CrudRepository<ParentAccount,Long> {
}
有人可以告诉我如何解决这个问题吗?我更喜欢使用EAGER fetch的解决方案。谢谢你的提示
编辑:这是我正在使用的架构
create table parent_account (
id BIGint auto_increment,name varchar(80) null,PRIMARY KEY (`id`)
);
create table linked_account (
id BIGint auto_increment,parent_account_id BIGINT,FOREIGN KEY (`parent_account_id`) REFERENCES `parent_account` (`id`),PRIMARY KEY (`id`)
);
以上是大佬教程为你收集整理的Spring Boot JPA-OneToMany关系导致无限循环全部内容,希望文章能够帮你解决Spring Boot JPA-OneToMany关系导致无限循环所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。