I'm having trouble to persist two transient 1:n-associated objects when using cascade "delete-orphan" without "save-update". Not using "delete-orphan" or using "save-update" works, but is not what is intended.
Hibernate version: 3.2.4.sp1 (though other version showed same behaviour)
A very small (artificial) sample looks like this
Code:
public class TestHibernate {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Item item = new Item();
item.setName( "Painting IX" );
Bid bid = new Bid();
bid.setAmount( 23 );
item.addBid( bid ); // sets both "sides"
session.save( item );
session.save( bid );
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
}
Here
Code:
HibernateUtil
resembles the class found in the hibernate tutorial, bid and item are two entities with the usual getters / setters for the mentioned fields with independent lifecycles.
The relevant parts of the two mappings are as follows:
Code:
<hibernate-mapping>
<class name="tests.Item" table="ITEMS">
<id name="id" column="ITEM_ID">
<generator class="native"/>
</id>
<property name="name"/>
<set name="bids" inverse="true" cascade="delete">
<key column="ITEM_ID" />
<one-to-many class="tests.Bid" />
</set>
</class>
</hibernate-mapping>
and
Code:
<hibernate-mapping>
<class name="tests.Bid" table="BIDS">
<id name="id" column="BID_ID">
<generator class="native"/>
</id>
<property name="amount"/>
<many-to-one name="item" column="ITEM_ID" class="tests.Item" not-null="true" />
</class>
</hibernate-mapping>
All of the above works as long as I do not use
Code:
delete-orphan
as an additional cascading option; I may write
Code:
delete-orphan
, if I additionally use
Code:
save-update
. Alas, all I really want, is just using
Code:
delete,delete-orphan
which throws an exception on
Code:
session.save( item );
namely a
Code:
TransientObjectException
saying
Code:
Exception in thread "main" org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: tests.Bid
Is there a way to persist two transient associated objects using a cascading "delete,delete-orphan"? Changing to a different (working) order like creating "item", persisting "item", creating "bid", persisting "bid" is not an option as the creation of the transient objects is not at my hand.
Many thanks for any helpful comments,
Alde.[/list]