【问题标题】:Hibernate: Bidirectional ManyToOne Mapping - inverse relation not working休眠:双向多对一映射 - 反向关系不起作用
【发布时间】:2017-08-28 07:46:05
【问题描述】:

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

我的 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 对象始终为空。

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

@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);

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

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

我似乎在某处有一个无限循环。有人可以指点我的解决方案吗?

【问题讨论】:

  • 这个 rbings 不成功意味着它没有返回结果或给出错误?
  • 一开始我以为它只是空值,但现在我在控制台中看到它抛出了一个错误。我会在几秒钟内更新我的描述

标签: java hibernate jpa many-to-one bidirectional


【解决方案1】:

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

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

如果您想对双方进行序列化,或者您可以寻求其他解决方案,请查看此post 以获取在没有无限递归的情况下继续对双方进行序列化的解决方案

【讨论】:

  • 非常感谢您的解释和帖子,这完全有道理!
【解决方案2】:

@JsonIgnore 可能会帮助您打破“无限递归”错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多