0

i am using Hibernate 4 as a ORM tool within a Angular/Spring/Oracle project.

I have a bidirectional @OneToMany relationship in my parent class Portfolio as below:

@OneToMany(mappedBy = "portfolio", fetch = FetchType.EAGER, cascade = { CascadeType.ALL }, orphanRemoval = true)
@JsonManagedReference
private Set<PortfolioContributors> portfolioContributors;

and a @ManyToOne relationship in my child entity PortfolioContributors.

@ManyToOne
@JoinColumn(name = "PORTFOLIO_ID", referencedColumnName = "PORTFOLIO_ID", foreignKey = @ForeignKey(name = "FK_PORTFOLIO_CONTRIBUTORS"), nullable = false)
@JsonBackReference
private Portfolio portfolio;

The problem is that if i remove a entry from the set of child entities in parent class. It does not set removed/ deleted from database.

How to achieve this behavior?

Predrag Maric
  • 23,938
  • 5
  • 52
  • 68

1 Answers1

1

You have to also set null on the other side of the relation. Something like this:

Portfolio portfolio = ...;
PortfolioContributors portfolioContributors = ...;

portfolio.getPortfolioContributors().remove(portfolioContributors);
portfolioContributors.setPortfolio(null);
Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
  • Hi @Predrag, i am just doing a Hibernate save(portfolio) and the portfolio object contains a set of all the valid portfolioContribuotrs. I am not manually removing portfolioContributors from portfolio etc. I want the portfolioContributor to get removed automatically if it is not in Set of Portfolio object. – Ankit Srivastava Aug 25 '16 at 14:35
  • Hibernate doesn't handle the other side of bidirectional relationship, you have to do that yourself. Your use case seems to be a little specific, but you will have to `setPortfolio(null)` on the `PortfolioContributors` instance you are removing and you'll need to save it since it is the owning side of the relation. – Predrag Maric Aug 25 '16 at 14:45
  • Check out the code examples in [Hibernate documentation](https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/example-parentchild.html#example-parentchild-cascades). Not exactly the same thing but close enough. Aslo check out [this SO thread](http://stackoverflow.com/a/23926548/4074715). – Predrag Maric Aug 25 '16 at 14:51
  • Thanks, I am not the one deciding what should be removed or added to the SET. User removes it in frontend and frontend sends Portfolio object to backend with a new SET which does not have the removed portfolioContributor. Not sure how i am supposed to figure all this out manually at backend. – Ankit Srivastava Aug 25 '16 at 14:55
  • 1
    I supposed orphanremoval = true was supposed to achieve the same behaviour. – Ankit Srivastava Aug 25 '16 at 14:58