Java – JPA onetoone bidirectional

I have two entity classes with @ onetoone relationships The example code is as follows:

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 is "I can use the seta (a a) method in group B. I mean 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 try this, foreign in table a (b_id)_ The key field is saved as null Please help me

Solution

Here, you have private a above class B; Mappedby. Is specified in In a two - way relationship, mapped by means that I am not the owner So this means that a is the owner of the relationship

In table a, you will have a foreign key for table B Since a is the owner, a assumes cascading operations to B. ideally, you should try a. setb() and persist a

Try the following:

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();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>