One-to-one: property-ref: foreign key: composite-id
Presently there is no way in hibernate using which we can specify one-to-one relationship with property-ref to part of composite-id
of another entity. The following scenario will clarify the above statement.
There is a one-to-one relationship between Product and ProductBasic.
Product -----> productId (PK)
ProductBasic ----> pId, useCode, StartTime (as composite key) and pId is also foreign key referencing Product.
This is a legacy database. We get one-to-one relationship by using the condition:
Product.productId=ProductBasic.pId and useCode='008' and startTime<currentTime<endTime.
<one-to-one name="productBasic" cascade="save-update" property-ref="activeProduct" constrained="true">
<key-property name="pId" column="PID" ></key-property>
<key-property name="useCode" column="USECODE" "></key-property>
<key-property name="startTime" column="STARTTIME" ></key-property>
<property name="compProductBasic.pId" class="Product" insert="false" update="false" lazy="proxy" />
If my relationship is Product.productId = ProductBasic.pId, there is no way in hibernate to specify this relationship.
Moreover we cannot remap(refer to) the property of composite-id (compProductBasic.pId in current example)..
Hence i request for enhancement in hibernate to incorporate this.
Hibernate Version 3.2.6, Database Db2
Ans B) The problem is of constrained="true" condition. It should be on proper one-to-one relationship.
For more details see Java Persistence With Hibernate book, section 7.1.1 The foreign identifier generator.
Now this issue if resolved. Please close this issue..
In Java Persistence With Hibernate, Section 8.1.1, Foreign keys in composite primary keys
<class name="User" table="USER">
<composite-id name="userId" class="UserId">
<key-property name="departmentId" column="DEPARTMENT_ID"/>
<many-to-one name="department" class="Department" column="DEPARTMENT_ID" insert="false" update="false"/>
UserId id = new UserId("johndoe", department.getId() );
User user = new User();
// Assign a primary key value
// Set property values
Only the identifier value of the department has any effect on the persistent state; the setDepartment(department) call is done for
Few Points on above codes
A) In java code, we are manually assigning value for departmentId (of UserId) from department property.
In true foreign key sense, this should be done automatically (by hibernate). Why user should assign value to
foreign key manually?
B) I guess this way also, there is a problem with ont-to-one relationship. Consider the above Product and ProductBasic
one-to-one relationship, Now i am manually assigning property to compProductBasic.pId.
When i call save(Product), it's first saving ProductBasic, which fails as ProductBasic has pid as foreign key. So
it's value should be present in parent table (product).. Is this a bug with one-to-one associations?
In this case Product should be inserted first followed by ProductBasic. Right?