Ankit Srivastava
Ankit Srivastava

Reputation: 45

Can we have a @OneToMany and @ManyToOne relationship between two tables in hibernate?

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 Stackoverflow on fetching them using JACKSON as a JSON

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

Upvotes: 1

Views: 86

Answers (1)

Bassem Salama
Bassem Salama

Reputation: 477

you need to add json ignore to one side of the relations 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;

}

Upvotes: 1

Related Questions