Reputation: 157
I have ManyToOne relation of two entities
@Entity(name = "foo")
public class Foo {
@Id
@Column(name = "fooId")
private Long id;
@ManyToOne(fetch = FetchType.EAGER,
targetEntity = Bar.class,
cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinColumn(name = "foo")
private Set<Bar> bars;
public Foo() {
bars = new HashSet<>();
}
public Set<Bar> getBars() {
return bars;
}
public void setBars(Set<Bar> bars) {
this.bars = bars;
}
}
@Entity(name = "bar")
public class Bar {
@Column(name = "fooId")
private Foo foo;
public Bar() {}
}
public class Persist {
@PersistenceContext(unitName = "myPersistUnit")
private EntityManager manager;
public static void main(String[] args) {
Foo f = new Foo();
f.getBars().add(new Bar());
manager.persist(f);
}
}
But when i call the Hibernate persist method, the Foo entity is saved sucessfull, but with Bar entity i got not-null violation in field foo;
Can somebody tell me what I'm missing?
Upvotes: 0
Views: 30
Reputation: 1942
You should set Foo entity reference in Bar Entity . It will solve your problem
Foo f = new Foo();
Bar bar=new Bar();
bar.setFoo(f);
f.getBars().add(bar);
manager.persist(f);
Upvotes: 1