i have defined following entities:
@entity public class child implements serializable { @id @manytoone(cascade = cascadetype.all) public parent parent; @id public int id; } @entity public class parent { @id public int id; }
when try persist child following code:
parent p = new parent(); p.id = 1; child c1 = new child(); c1.id = 1; c1.parent = p; em.persist(c1);
hibernate throws 'referential integrity constraint violation' error:
caused by: org.h2.jdbc.jdbcsqlexception: referential integrity constraint violation: "fk3e104fc802aac0a: public.child foreign key(parent_id) references public.parent(id) (1)"; sql statement: insert child (parent_id, id) values (?, ?) [23506-171]
i believe because first inserts child , parent, while expect insert parent first. idea how can change order of insertion, or how to solve in other way?
update: note approach not jpa compliant, uses hibernate specifics (see section 5.1.2.1. composite identifier in hibernate docs)
update: have persist child c1 , have persist cascade parent p automatically (this update in reaction @alf's answer below).
em.persist(p); em.persist(c1);
update
i think problem code not jpa compliant. try embeddedid, works me.
@embeddable public class childpk implements serializable { private int parentid; private int childid; // getters , setters } @entity public class child implements serializable { @embeddedid public childpk id = new childpk(); @mapsid( "parentid" ) @manytoone public parent parent; } parent p = new parent(); p.id = 1; child c1 = new child(); c1.id.setchildid( 1 ); c1.parent = p; em.persist( c1 );
i think works @idclass
too, never used it.
Comments
Post a Comment