I'm new to Hibernate and am trying to understand what is happening under the hood with my object constructors. Here is my scenario:
2 objects - ServiceRequest and ServiceMethod. Each one sets a timestamp in the constructor when the object is created. ServiceRequest contains a reference to ServiceMethod (private field with get/set methods). What I want is the following: only one session.save() call using the ServiceRequest object, ServiceMethod is not created until it is needed (so that it's timestamp is an acurate reflection of the order of events).
Here's the order I do things...
* create ServiceRequest
* save ServiceRequest (ServiceMethod is null)
* ServiceRequest.getServiceMethod
* oh it's null - create ServiceMethod and ServiceRequest.setServiceMethod
* save ServiceRequest (ServiceMethod is not null)
I have this working, but I don't like that I have to explicitly do that null handling. I tried having getServiceMethod do the null check and create the ServiceMethod but Hibernate appeared to be calling this when saving the ServiceRequest the first time which meant that the timestamp on the object was not in the right sequence and that the object was written to the database before I wanted it to be (because I want to use cascade:save-or-update to make my save calls more bulletproof).
I like that Hibernate encourages me to think of these timestamp issues in the object layer (instead of the database layer where I usually punt it to) since they are object layer concerns. Is there a better design I can use to work with Hibernate and either tell it to create the object but not write it to the db (e.g. if certain fields are null despite the save-or-update call) or maybe setup the mapping better to handle this situation.
thx
Hibernate version:
2.1.7
Mapping documents:
Code:
<class name="testservice.ServiceMethod" table="method">
<id name="id" type="integer" unsaved-value="0">
<generator class="identity"/>
</id>
<property name="requestFilename" column="request_file"/>
<property name="responseFilename" column="response_file"/>
<property name="createMillis" column="create_dt"/>
<property name="modifiedMillis" column="mod_dt"/>
</class>
<class name="testservice.ServiceRequest" table="request">
<id name="id" type="integer" unsaved-value="0">
<generator class="identity"/>
</id>
<property name="ipAddress" column="ip_address"/>
<property name="username" column="username"/>
<property name="createMillis" column="create_dt"/>
<property name="modifiedMillis" column="mod_dt"/>
<many-to-one name="client" class="testservice.ServiceClient" column="client_id" not-null="true"/>
<many-to-one name="method" class="testservice.ServiceMethod" column="method_id" cascade="save-update"/>
</class>
Code between sessionFactory.openSession() and session.close():Code:
sess.saveOrUpdate(request);
sess.flush();
Full stack trace of any exception that occurs:n/a
Name and version of the database you are using:MySQL 3.23.x[/code]