JPA - difference in the use of the mappedBy property to define the owning entity

前端 未结 4 1510
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 06:41

What exactly is the difference in the following two declarations

B is the owning side

@Entity
class A {
   @Id int id;

   @OneToOne
   B b;
}

@Enti         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 07:30

    The owning side is the side that JPA considers to know is the association exists or not. Suppose you go with your first example. The owning side is the side where there is no mappedBy attribute. The owning side is thus A, and not B.

    This means that if you have an A and a B in database, and you do

    A a = em.find(A.class, aId);
    B b = em.find(B.class, bId);
    a.setB(b);
    

    JPA will save the association (i.e. it will store the ID of B in the join column of table A).

    But if you do

    A a = em.find(A.class, aId);
    B b = em.find(B.class, bId);
    b.setA(a);
    

    nothing will be changed in database, because you modified the inverse side and forgot to modify the owning side.

提交回复
热议问题