Hibernate version:
3.2
Mapping documents:
Code:
<class name="model.Parent" table="parents">
<id name="id" column="id"><generator class="native"/></id>
<property name="name"/>
<set name="children" order-by="id" cascade="all-delete-orphan">
<key column="parent_id"/>
<one-to-many class="model.Child"/>
</set>
</class>
<class name="model.Child" table="children">
<id name="id" column="id"><generator class="native"/></id>
<property name="name"/>
<many-to-one name="parent" column="parent_id" insert="false" update="false" not-null="true" class="model.Parent" />
</class>
Code between sessionFactory.openSession() and session.close():Code:
//get the first parent from the table
Parent p = (Parent)allParents.get(0);
//create a child
Child foo = new Child();
foo.setName("foo");
//add it to the parent's set of children
p.getChildren().add(foo);
//also set the child's parent
foo.setParent(p);
Name and version of the database you are using:MySQL or SQL Server
The generated SQL (show_sql=true):Code:
insert into children (name, parent_id) values (?, ?)
update children set parent_id=? where id=?
Hello
These are my mappings. I create a new Child and add it in the list of children of the first Person object. My problem is that hibernate first does an insert in the children table (with parent_id
NULL) and then updates that same row to set the parent_id.
Hibernate already knows which is the parent of the new child it is inserting in the database.
Is there a way to have it do that with a single query?
thanks,
Ioannis