我们可以在hibernate中的两个表之间建立@OneToMany和@ManyToOne关系吗?

时间:2016-12-06 20:41:14

标签: java json spring hibernate jackson

例如

public class Portfolio implements Serializable {

    @ManyToOne()
    @JoinColumn(name = "PORTFOLIO_OWNER", referencedColumnName = "USER_ID", foreignKey = @ForeignKey(name = "FK__USER__PORTFOLIO"), nullable = false)
    private User portfolioOwner;

    @ManyToOne()
    @JoinColumn(name = "ACCOUNT_CAPTAIN", referencedColumnName = "USER_ID", foreignKey = @ForeignKey(name = "FK__USER__PORTFOLIO2"))
    private User accountCaptain;

}

public class User {

    @ManyToOne
    @JoinColumn(name = "PORTFOLIO_ID", referencedColumnName = "PORTFOLIO_ID", foreignKey = @ForeignKey(name = "FK_DEF_PORTFOLIO_USER"))
    @Fetch(FetchMode.JOIN)
    private Portfolio defaultPortfolio;

}

我在使用JACKSON作为JSON

获取它们时遇到了Stackoverflow
  

org.springframework.http.converter.HttpMessageNotWritableException:   无法写内容:无限递归(StackOverflowError)   (通过参考链:   com.User [" defaultPortfolio"] - > com..Portfolio [" portfolioOwner"] - > com.User [" defaultPortfolio"] - >玉米.Portfolio [" portfolioOwner"] - > com..User [" defaultPortfolio"] -

1 个答案:

答案 0 :(得分:1)

你需要将json ignore添加到关系ex:

的一侧
public class Portfolio implements Serializable {

    @ManyToOne()
    @JoinColumn(name = "PORTFOLIO_OWNER", referencedColumnName = "USER_ID", foreignKey = @ForeignKey(name = "FK__USER__PORTFOLIO"), nullable = false)
    @JsonIgnore
    private User portfolioOwner;

    @ManyToOne()
    @JoinColumn(name = "ACCOUNT_CAPTAIN", referencedColumnName = "USER_ID", foreignKey = @ForeignKey(name = "FK__USER__PORTFOLIO2"))
    private User accountCaptain;

}