I'm a little confused about how Hibernate manages objects.
Here are (hopfully relevant) parts of two mapping files:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class dynamic-insert="false" dynamic-update="false" lazy="false" mutable="true" name="tciworks.drugmodel.AbstractDrugModel" optimistic-lock="version" polymorphism="implicit" select-before-update="false" table="Drug">
<id column="Name" name="name"/>
<discriminator column="DrugModelType"/>
...
</class>
</hibernate-mapping>
Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class dynamic-insert="false" dynamic-update="false" mutable="true" name="tciworks.course.model.Course" optimistic-lock="version" polymorphism="implicit" select-before-update="false" table="Course">
<id column="CourseIdentifier" name="courseID" unsaved-value="-1">
<generator class="native"/>
</id>
<property column="CourseNo" name="courseNo"/>
<many-to-one column="PatientIdentifier" foreign-key="PatientIdentifierFK" name="patient" not-null="true"/>
<many-to-one column="DrugName" foreign-key="DrugNameFK" lazy="false" name="drug" not-null="true"/>
...
</class>
</hibernate-mapping>
I have some unit tests which first create and save a sub-class of AbstractDrugModel, and then retrieve this from the database (I have found that retrieving it returns a different referene from the original AbstractDrugModel instance that I've created) and hold an instance to it. I then create and save a course, setting the retrieved instance of AbstractDrugModel and save the course.
What I have found is that when I save the course, the reference value of the drug I have maintained changes (looking in the debugger), but the reference of the drug in the course that I have saved is updated. I find this very confusing, and furthermore difficult to maintain only a single instance of the same drug.
Is there a way to stop this happening? I was looking at the update options but they didn't seem to help. I wonder how many other things are going to catch me out with this behaviour.
Thanks
Lionel.