Hi All, I'm using Hibernate 3.2.0 and I have the following problem relating to mapping two entities:
USER:
- username (PK)
INDIVIDUAL:
- id (PK)
- username (FK)
Basically, a USER can map to 0 to 1 INDIVIDUALs, and an INDIVIDUAL can map to 0 to 1 USERs. So basically it's an optional one-to-one relationship (is that makes sense).
I've managed to map this as follows:
User.hbm.xml:
Code:
<hibernate-mapping>
<class name="com.test.User" table="USER">
<id name="username" column="USERNAME">
<generator class="assigned" />
</id>
<one-to-one name="individual" property-ref="username"/>
</class>
</hibernate-mapping>
Individual.hbm.xml:
Code:
<hibernate-mapping>
<class name="com.test.Individual" table="INDIVIDUAL">
<id name="id" type="long" column="ID">
<generator class="sequence"/>
</id>
<property name="username" column="USERNAME" />
<!-- actually a one-to-one association due to "unique=true" -->
<many-to-one name="user" column="username" unique="true" not-null="false"/>
</class>
</hibernate-mapping>
And here are my domain models:
Code:
public class User {
private String username;
private Individual individual;
/* getters and setters here */
}
public class Individual {
private Long id;
private String username;
private User user;
/* getters and setters here */
}
This works, but I find it a little unsafe having to expose "username" in my Individual.hbm.xml mapping and Individual.java. I'd rather keep that hidden in the Java side of things since it's a foreign key.
Any ideas? I've tried to implement a many-to-many mapping on both entities with unique="true" and not-found="ignore" options, but this keeps throwing errors.
Thanks in advance for any help you can give.