Hibernate

adplus-dvertising
One to One Mapping
Previous Home Next

One to One association is represent that another persistent class is declared using a one to one element.


<one-to-one 
	name="propertyName"  
	class="ClassName"  
	cascade="cascade_style"  
	constrained="true|false"  
	fetch="join|select"  
	property-ref="propertyNameFromAssociatedClass"  
	access="field|property|ClassName"  
	formula="any SQL expression"  
	lazy="proxy|no-proxy|false"  
	entity-name="EntityName"  
	node="element-name|@attribute-name|element/@attribute|." embed-xml="true|false" foreign-key="foreign_key_name" 
/>

In hibernate we found the two varieties of one-to-one associations:

  1. Primary key associations
  2. Unique foreign key associations

In the one to one association we don't need to add extra table column. when if two rows are related by the association then two table rows share primary key value. Two object by a primary key association relate to ensure that they are assigned the same identifier value.

For a primary key association, add the following mappings to Employee and Person respectively:


<one-to-one name="person" class="Person"/>
<one-to-one name="employee" class="Employee" constrained="true"/>

Ensure that the primary keys of the related rows in the PERSON and EMPLOYEE tables are equal.

for calling the foreign key strategy we need to use special Hibernate identifier generation strategy:

Some Other Hibernate Related links


<class 
	name="person" 
	table="PERSON"> 
<id 
	name="id" 
	column="PERSON_ID"> 
<generator class="foreign"> 
<param name="property">employee</param> 
</generator> </id> ... <one-to-one name="employee" class="Employee" constrained="true"/> 
</class>

A newly saved instance of Person is assigned the same primary key value as the Employee instance referred with the employee property of that Person.

Foreign key with a unique constraint, from Employee to Person, can be expressed as:


 <many-to-one name="person" class="Person" column="PERSON_ID" unique="true"/>

This association can be made bidirectional by adding the following to the Person mapping:


<one-to-one name="employee" class="Employee" property-ref="person"/>

Previous Home Next