I had a very
similar problem yesterday and fixed it (with help) but after refactoring something very similar seems to have come back to haunt me!
I have a parent/child relentionship and would like to save the parent and have the child automatically persisted/saved.
ParentCode:
<set name="habitTrackerTrackerUserDatas" inverse="true" lazy="true" table="habitTrackerTrackerUserData" cascade="persist,merge,save-update" fetch="select">
<key>
<column name="tracker_id" />
</key>
<one-to-many class="uk.co.prodia.prosoc.domainmodel.HabitTrackerTrackerUserData" />
</set>
ChildCode:
<many-to-one name="habitTrackerTracker" class="uk.co.prodia.prosoc.domainmodel.HabitTrackerTracker" fetch="select">
<column name="tracker_id" />
</many-to-one>
Hibernate is performing the following SQL statements:
Code:
insert into habittracker.habitTrackerTracker (yaxis_start, yaxis_end, yaxis_increment) values (?, ?, ?);
update habittracker.habitTrackerTrackerUserData set user_id=?, tracker_id=?, tracker_name=? where user_data_id=?
If I save the parent the following happens:
- It saves the parent;
- Then tries to update the child which fails as the child has not yet been saved;
- A RollbackException is thrown and the data is not committed to the DB.
If I save the child this happens instead:
- It tries to save the child but fails as the parents id is null.
Any suggestion or links to docs appreciated. I have looked through several parent/child documents from the manual as well as the
Transitive persistence but I am obviously missing something.