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

后端 未结 3 830
生来不讨喜
生来不讨喜 2020-11-30 12:22

I have a really simple setup to try out a bidirectional mapping with annotations:

@Entity
public class TypeA extends AbstractModel {

    @Id
           


        
3条回答
  •  死守一世寂寞
    2020-11-30 12:31

    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.

提交回复
热议问题