【问题标题】:Spring boot JPA bidirectional infinite cycle issueSpring boot JPA双向无限循环问题
【发布时间】:2020-05-16 17:22:22
【问题描述】:

我有一个使用 Spring Boot 和 Spring JPA 2.2.7.RELEASE 的 Java 14 项目。假设我们有 2 个实体:

玩家实体:

@OneToOne(mappedBy = "player", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
private GameEntity game;

游戏实体:

@JoinColumn(name = "player_id")
@OneToOne(fetch = FetchType.LAZY)
private PlayerEntity player;

我在映射、从数据库中获取这些实体以及所有其他相关操作时遇到问题。我得到一个无限循环,因为这两个实体不断调用自己,比如这个 GameEntity -> PlayerEntity -> GameEntity 等等。

我在使用 DTO 并将它们作为 JSON 返回时遇到了同样的问题(我得到了一个“永无止境的”json,这些对象无休止地相互包裹)。我想将关系的一部分标记为@JsonIgnore,但我不知道如何处理这些实体。

我想从双方(双向)访问,以便始终填充这些对象。是否可以不用在一侧/两侧用 id 替换实际对象?我已经阅读了一些 Spring JPA 文档和其他相关手册,根据它们,双向关系比单向关系更好,但是如何在遇到此类问题时实现这一点?

感谢您对此事的任何提示。如果这种模式是可能的,我将非常感谢每一个为我指明正确方向的提示。

编辑:

这实际上是 BoardEntity 和 GameEntity 的示例,但它与 PlayerEntity 和 GameEntity 的逻辑相同。堆栈跟踪:

org.springframework.http.converter.HttpMessageNotWritableException: 无法写入 JSON:无限递归(StackOverflowError);嵌套的 例外是 com.fasterxml.jackson.databind.JsonMappingException: 无限递归(StackOverflowError)(通过引用链: pl.nombritech.squareconomy.model.entity.GameEntity["board"]-pl.nombritech.squareconomy.model.entity.BoardEntity["game"]-pl.nombritech.squareconomy.model.entity.GameEntity["board"] -pl.nombritech.squareconomy.model.entity.BoardEntity["game"]-pl.nombritech.squareconomy.model.entity.GameEntity["board"]-pl.nombritech.squareconomy.model.entity.BoardEntity["game" ]-pl.nombritech.squareconomy.model.entity.GameEntity["board"]-

等等……

【问题讨论】:

标签: java spring hibernate spring-boot jpa


【解决方案1】:

使用

玩家实体:

@JsonManagedReference
@OneToOne(mappedBy = "player", cascade = CascadeType.ALL, fetch = 
FetchType.LAZY, orphanRemoval = true)
private GameEntity game;

游戏实体:

  @JsonBackReference
  @JoinColumn(name = "player_id")
  @OneToOne(fetch = FetchType.LAZY)
  private PlayerEntity player;

反之亦然。

【讨论】:

    猜你喜欢
    • 2017-01-09
    • 2021-08-25
    • 2021-12-23
    • 2016-01-18
    • 2013-01-05
    • 2022-01-15
    • 2018-08-02
    • 2015-05-17
    • 1970-01-01
    相关资源
    最近更新 更多