休眠:双向ManyToOne映射 - 逆关系不起作用

问题描述:

我在创建两个域类的双向映射时遇到问题。休眠:双向ManyToOne映射 - 逆关系不起作用

我有我的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 (*Error); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (*Error) (through reference chain: com.david.coinlender.domain.UserAccount["accountTransactions"]->org.hibernate.collection.internal.PersistentBag[0]->com.david.coinlender.domain.AccountTransaction["userAccount"] 

我似乎有一个无限循环的地方。有人能指点我的解决方案吗?

+0

这种冲突不成功意味着它返回没有结果或它给出错误? –

+0

首先,我认为它只是null,但现在我在控制台看到它会引发错误。我会在一秒钟内更新我的描述 – dave0688

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

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

,或者你可以去其他的解决方案,如果你愿意序列双方关系,检查此post的解决方案,以保持序列化两侧没有无限递归

+0

非常感谢解释和帖子,这是完全合理的! – dave0688

@JsonIgnore可以帮助你打破'Infinete递归'错误。