JPA OneToOne bidirectional .
19,365
Solution 1
Here , you have specified mappedBy
in class B above private A a;
. In a bidirectional relationship , mappedBy
means that I am not the owner. So It means that A is the owner of the relationship.
In table of A , you will have a foreignkey for table of B. As A is the owner, A is suppose to cascade operations to B. Ideally you should try a.setB()
and then persist a.
Try below:
em.getTransaction().begin();
//first create B.
B bb = new B();
bb.setId(1);
bb.setName("CC");
em.persist(bb);
//create A with B set in it.
A aa = new A();
aa.setId(1);
aa.setName("JJ");
aa.setB(bb);
em.persist(aa);
em.getTransaction().commit();
Or
em.getTransaction().begin();
//first create B.
B bb = new B();
bb.setId(1);
bb.setName("CC");
// no need to persist bb.
//create A with B set in it.
A aa = new A();
aa.setId(1);
aa.setName("JJ");
aa.setB(bb);
em.persist(aa); // because of cascade all , when you persist A ,
// B will also be persisted.
em.getTransaction().commit();
Solution 2
Use @Cascade({CascadeType.SAVE_UPDATE}) to cascade changes
public class B {
@Id
private int id;
private String name;
@OneToOne(mappedBy="b")
@Cascade({CascadeType.SAVE_UPDATE})
private A a;
//setter and getters
}
Comments
-
Ye Kyaw Kyaw Htoo over 1 year
I have two entity classes that are in @OneToOne relation. The example code are as follow:
public class A { @Id private int id; private String name; @JoinColumn(name = "B_ID", referencedColumnName = "id") @OneToOne(cascade=CascadeType.ALL) private B b; //setters and getters } public class B { @Id private int id; private String name; @OneToOne(mappedBy="b") private A a; //setter and getters }
my question here is "Can I use setA(A a) method in class B. I mean like this . .
em.getTransaction().begin(); A aa = new A(); aa.setId(1); aa.setName("JJ"); em.persist(aa); B bb = new B(); bb.setId(1); bb.setName("CC"); bb.setA(aa); em.persist(bb); em.getTransaction().commit();
When I tried like this, the foreign_key field in table A (B_ID) was saved as null.
Please help me. -
Ye Kyaw Kyaw Htoo almost 11 yearsthen fri, what would be the differences between unidirectional and bidirectional in @OneToOne relationship ..? thanks for your answer!
-
Chris almost 11 yearsUnidirectional means you only have a relationship going one way, and that relationship controls the foreign key. Bidirectional has a unidirectional component - a relationship that controls the foreign key in the database, and a read-only back pointer going the other way. The relationship marked mappedby is effectively read only, in that it uses the relationship set on the other entity, but changes to this relationship will not change the database. JPA requires that you maintain both sides of a bidirectional relationship to keep the cached entities insynch with the database
-
meliniak over 6 years@PriyankDoshi can you elaborate why it is not?