JPA OneToOne bidirectional .

旧街凉风 提交于 2019-12-05 23:39:23

问题


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.


回答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();



回答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

}



回答3:


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

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