java - When inserting a parent and its children can Hibernate set the parent id when inserting the child rather than having to update after? -
i have 2 objects
public class parent { int id; string name; int set<child> children; } public class child { int id; string name; int parentid; }
with following mapping file
<hibernate-mapping> <class name="parent" table="parent"> <id column="id" access="field"> <generator class="identity"/> </id> <property name="name" column="name" access="field" /> <set name="children" access="property" cascade="all" lazy="true" > <key><column name="parent_id"/></key> <one-to-many class="com.hp.autonomy.corepolicy.common.dto.lexiconexpression"/> </set> </class> <class name="child" table="child"> <id column="id" access="field"> <generator class="identity"/> </id> <property name="name" column="name" access="field" /> <property name="parentid" column="parent_id" access="field" not-null="true" /> </class> </hibernate-mapping>
when save parent 1 child sql generated looks
hibernate: insert parent (id, name) values (null, ?)
hibernate: insert child (id, parent_id, name) values (null, ?, ?)
hibernate: update child set parent_id=? id=?
it seems when hibernate inserts child sets parent_id null , comes , updates after. causes problems in database , hibernate validation, schema says parent_id cannot null.
is possible have second insert statement use parent_id created when inserting parent rather coming along later , updating child?
you need change
<property name="parentid" column="parent_id" access="field" not-null="true" />
by
<many-to-one name="parent" class="change parent classname"> <column name="parent_id" not-null="true" access="field"/> </many-to-one>
you need change child
class have parent
member instead of parentid
, update config above accordingly.
Comments
Post a Comment