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

时间:2021-08-27 19:18:00

Eg.

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;

}

and

public class User {

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

}

I run into * on fetching them using JACKSON as a JSON

我在使用JACKSON作为JSON获取它们时遇到了*

org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Infinite recursion (*Error) (through reference chain: com.User["defaultPortfolio"]->com..Portfolio["portfolioOwner"]->com.User["defaultPortfolio"]->com.Portfolio["portfolioOwner"]->com..User["defaultPortfolio"]-

org.springframework.http.converter.HttpMessageNotWritableException:无法写入内容:无限递归(*Error)(通过引用链:com.User [“defaultPortfolio”] - > com..Portfolio [“portfolioOwner”] - > com.User [ “defaultPortfolio”] - > com.Portfolio [ “portfolioOwner”] - > com..User [ “defaultPortfolio”] -

1 个解决方案

#1


1  

you need to add json ignore to one side of the relations ex:

你需要将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;

}

#1


1  

you need to add json ignore to one side of the relations ex:

你需要将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;

}