Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp
Hibernate version:
3.0.5
Mapping documents:
Code:
<class name="Customer">
<id name="id" type="java.lang.Long">
<generator class="native" />
</id>
<version name="version" />
<set name="sites" cascade="all" inverse="true">
<key column="customer_id" />
<one-to-many class="Site" />
</set>
<set name="positions" cascade="all" inverse="true">
<key column="customer_id" />
<one-to-many class="Position" />
</set>
</class>
Code:
<class name="Site">
<id name="id" type="java.lang.Long">
<generator class="native" />
</id>
<many-to-one name="customer" class="Customer" not-null="true" />
<set name="positions" cascade="all">
<key column="site_id" />
<one-to-many class="Position" />
</set>
</class>
Code:
<class name="Position">
<id name="id" type="java.lang.Long">
<generator class="native" />
</id>
<many-to-one name="site" class="Site" />
<many-to-one name="customer" class="Customer" not-null="true" />
</class>
Hey folks. I'm trying to implement an application using a session per request with detached objects pattern. A simplified version of the mapping documents are shown above. Basically, a Customer has many sites and many positions, and any position may optionally be associated with a site. Sites and positions may be added and removed, but none of these changes may be commited to the database until the user hits save.
At the beginning of the application transaction, a customer is loaded, then placed into the HttpSession. On each subsequent request, before anything else happens, I reattach the customer to the new session with the following code:
Code:
Session session = HibernateSessionFactory.currentSession();
session.setFlushMode(FlushMode.NEVER);
session.update(customer);
This is to prevent lazy loading exceptions. Lock doesn't seem to work in my situation as the customer object is probably modified. Flushmode is set to never to ensure the changes aren't committed until the user presses save.
When I finally DO want the changes persisted, I call session.flush(). This is where things break down.
Basically, it appears that Hibernate is losing track of what is dirty. For example, if I add a site to the customer, then add a position, then click save, only the position is saved. If the new position is associated with the new site the flush fails with a ConstraintViolationException, as the site's id isn't in the database when it sets the foreign key.
If I fully populate the customer object when it's initially loaded, omit the setFlushMode and the update, and then call merge on save, all works as expected. However, the customer object can get fairly large, and I'd rather not store the whole thing in HttpSession if I can avoid it.
Does anyone have any idea what I'm doing wrong? If it's not obvious, I can write up a test case.
Scott