关于Java:Spring Boot JPA双向无限循环问题

Spring boot JPA bidirectional infinite cycle issue

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

PlayerEntity:

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

GameEntity:

1
2
3
@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:
Could not write JSON: Infinite recursion (StackOverflowError); nested
exception is com.fasterxml.jackson.databind.JsonMappingException:
Infinite recursion (StackOverflowError) (through reference chain:
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"]-

依此类推...


使用

PlayerEntity:

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

GameEntity:

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

反之亦然。