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.
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();
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
}
you need to add aa.setB(bb) before em.persist(bb)
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");
aa.setB(bb);//this line should be added
bb.setA(aa);
em.persist(bb);
em.getTransaction().commit();
来源:https://stackoverflow.com/questions/14746318/jpa-onetoone-bidirectional