I have a single 'User' entity that is used with a unique 'one-to-many' relationship with many of my other entites. e.g:
Code:
<class name="xxx.yyy.zzz..UserReference">
<id name="id" column="id" unsaved-value="null">
<generator class="native" />
</id>
<property name="userId" unique="false" not-null="true"/>
<property name="userName" unique="false" not-null="true"/>
</class>
<class name="xxx.yyy.zzz..SomeEntityA" >
...
<many-to-one
name="usertReference"
column="userreferenceid"
class="xxx.yyy.zzz..UserReference"
cascade="save-update"
not-null="true"
unique="true"
/>
...
</class>
<class name="xxx.yyy.zzz..SomeEntityB">
...
<many-to-one
name="usertReference"
column="userreferenceid"
class="xxx.yyy.zzz..UserReference"
cascade="save-update"
not-null="true"
unique="true"
/>
...
</class>
etc.
The pattern above exists all over the domain and works in part. The problem is that user reference is created multiple times over and over event hough the 'user.id' and 'user.name' fields are unique.
In other words I should have one user entry per user (it is an entity after all). If I set the uniqueness constraints on the user entity to 'true' in the mapping:
Code:
<class name="xxx.yyy.zzz..UserReference">
<id name="id" column="id" unsaved-value="null">
<generator class="native" />
</id>
<property name="userId" unique="true" not-null="true"/>
<property name="userName" unique="true" not-null="true"/>
</class>
Then I get an error (as expected I guess).
My question is therfore: "How can I make it such that these 'UserReferences' are unique and each referencing entity references a single instance of the user instead of creating duplicate user records?
NB: I have implemented hashCode() and equals() correctly, but, it is difficult to maintain 'UserReference' object identity as sometimes these objects are returned in hibernated query results, and some times have to be created from XML request parameters, and sometimes created in the code base.
I am using Hibernate 3.2 and Postgres 8.2.
Thanks!