我有两个具有简单@OneToMany 关系的对象,如下所示:
parent :
@Entity
public class ParentAccount {
@Id
@GeneratedValue
private long id;
private String name;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "parentAccount")
private Set<LinkedAccount> linkedAccounts;
}
child :
@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,
name VARCHAR(80) null,
FOREIGN KEY (`parent_account_id`) REFERENCES `parent_account` (`id`),
PRIMARY KEY (`id`)
);
最佳答案
正如第一个答案所暗示的:
Do not use Lombok's
@Data
annotation on@Entity
classes.
原因 @Data
生成hashcode()
、equals()
和toString()
使用生成的 getter 的方法。使用 getter 意味着获取新数据,即使该属性标记为 FetchType=LAZY。
hibernate 在某处尝试使用 toString()
记录数据,但它崩溃了。
关于java - Spring Boot JPA - OneToMany 关系导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33234546/