Hibernate bidirectional @ManyToOne, updating the not owning side not working

For a consistent domain model you should always set both sides of the relation, like this:

TypeB b = new TypeB();

TypeA a = new TypeA();
a.setBs(ListUtils.createList(b));
b.setA(a);   

this.typeBDao.save(b);
this.typeADao.save(a);

When your entities are in an inconsistent state, JPA will always store values according to the object state of the owning side of the JPA relation. In this case TypeB owns the relation to TypeA. Thus if an object of TypeB does not have a reference to TypeA, JPA assumes there is no relation defined.

Leave a Comment