小编典典

Spring Boot JPA-OneToMany关系导致无限循环

spring-boot

我有两个具有简单@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,
    name VARCHAR(80) null,
    FOREIGN KEY (`parent_account_id`) REFERENCES `parent_account` (`id`),
    PRIMARY KEY (`id`)
);

阅读 879

收藏
2020-05-30

共1个答案

小编典典

问题解决了。我@toString在LinkedAccount中使用自定义方法,该方法引用了ParentAccount。我不知道这会导致任何问题,因此我没有在问题中包含toString。

显然,这导致了延迟加载的无限循环,删除此引用可解决此问题。

2020-05-30