Hibernate:双向 ManyToOne 映射 - 反向关系不起作用

Hibernate: Bidirectional ManyToOne Mapping - inverse relation not working

我在创建两个域的双向映射时遇到问题 类。

我的 UserAccount.java 有很多 AccountTransactions。在 AccountTransaction 域对象中,有一列 user_account_id 带有外键。

我已经按照以下方式设置了映射:

UserAccount.java

// Other properties 

@ManyToOne(optional = false)
@JoinColumn(name = "user_account_id")
@NotNull
private UserAccount userAccount;

// Getters and setters...

AccountTransaction.java

@OneToMany(cascade=CascadeType.ALL, mappedBy="userAccount")
public List<AccountTransaction> accountTransactions;

场景是我想获取所有 userAccounts 的列表及其相应的 accountTransactions 作为 JSON 数组,但 accountTransactions 对象始终为 null。

我也尝试过在存储库中修改查询:

@Query("SELECT account FROM UserAccount account JOIN FETCH account.accountTransactions WHERE account.user = :systemUser AND account.adminAccount = TRUE")
List<UserAccount> findAllAdminAccountWithTransactions(@Param("systemUser") User systemUser);

当我通过此查询检索值时,它首先 returns 存储库中的所有内容都是正确的。但随后它抛出异常:

c.d.c.w.rest.errors.ExceptionTranslator  : An unexpected error occurred: Could not write JSON: Infinite recursion (WhosebugError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (WhosebugError) (through reference chain: com.david.coinlender.domain.UserAccount["accountTransactions"]->org.hibernate.collection.internal.PersistentBag[0]->com.david.coinlender.domain.AccountTransaction["userAccount"]

我好像在某个地方有一个无限循环。有人可以指出解决方案吗?

因为这是一个双向关系,jackson 会尝试从另一部分序列化关系的每一部分,所以是的,你将有无限递归,为了避免这种情况,你需要通过停止序列化的一侧来停止循环使用@JsonIgnore

的关系
 @JsonIgnore
 @ManyToOne(optional = false)
 @JoinColumn(name = "user_account_id")
 @NotNull
 private UserAccount userAccount;

或者如果你想序列化双方,你可以寻求其他解决方案,检查这个post解决方案,以在没有无限递归的情况下保持双方的序列化

@JsonIgnore 可能会帮助您解决 'Infinete Recursion' 错误。