JPA OneToOne bidirectional .

泄露秘密 提交于 2019-12-04 04:46:11

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();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!