java - JPA OneToOne bidirectional . -
java - JPA OneToOne bidirectional . -
i have 2 entity classes in @onetoone relation. illustration code follow:
public class { @id private int id; private string name; @joincolumn(name = "b_id", referencedcolumnname = "id") @onetoone(cascade=cascadetype.all) private b b; //setters , getters } public class b { @id private int id; private string name; @onetoone(mappedby="b") private a; //setter , getters }
my question here "can utilize seta(a a) method in class b. mean . .
em.gettransaction().begin(); 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 tried this, foreign_key field in table (b_id) saved null. please help me.
here , have specified mappedby
in class b above private a;
. in bidirectional relationship , mappedby
means not owner. means owner of relationship.
in table of , have foreignkey table of b. owner, suppose cascade operations b. ideally should seek a.setb()
, persist a.
try below:
em.gettransaction().begin(); //first create b. b bb = new b(); bb.setid(1); bb.setname("cc"); em.persist(bb); //create b set in it. 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 persist bb. //create b set in it. aa = new a(); aa.setid(1); aa.setname("jj"); aa.setb(bb); em.persist(aa); // because of cascade , when persist , // b persisted. em.gettransaction().commit();
java jpa jpa-2.0
Comments
Post a Comment