JPA - difference in using the mappedBy property to determine the owner object

What is the difference in the next two ads

B - own side

@Entity
class A {
   @Id int id;

   @OneToOne
   B b;
}

@Entity
class B {
   @Id int id;

   @OneToOne(mappedBy="b")
   A a;
}

A - own side

@Entity
class A {
   @Id int id;

   @OneToOne(mappedBy="a")
   B b;
}

@Entity
class B {
   @Id int id;

   @OneToOne
   A a;
}

Thinking about it in “normal SQL”, I think it’s the same as having two tables, each of which has the foreign key of another table. However, I do not understand what the effect of determining which object belongs to a party using the "mappedBy" property. What this actually achieves, since I do not believe that there is an equivalent in normal SQL.

+5
source share
4 answers

JPA 2.0 Specification , Section 2.9, writes:

. , ( ) . . , 3.2.4.

:

  • , mappedBy OneToOne, OneToMany ManyToMany. mappedBy , .
  • "--/--" -, mappedBy ManyToOne.
  • - - , .
  • " " -.

3.2.4:

. , .

, . , , , , , , . " " " " , .

, , , .

+10

, , - . OO perspecitve, , db, rdbm .

OO , . , OrderLines. , . OrderLine, , , . , -.

, , @JB Nizet.

2.9 JPA 2.0 spec:

- , .

:

, : [..] "--", "--" / " " "--" .

:

(, ) , 2.10. , FK OneToOne .

, .

, , , 2.1 . , .

+6

A 2 id b_id, B , id. A .

B -. B , id a_id. A , id.

: -)

+4

- , , JPA, , . , . - , mappedBy. , , A, B.

, A B,

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

JPA will save the association (i.e., store identifier 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 the database because you changed the back side and forgot to change your side.

+3
source

All Articles