Wednesday, January 25, 2012

Hibernate : Component Mapping

Overview:
This article looks at how you can map data in a given table across several POJOs treated as components of another POJO.

Association Diagram
__________
|Person |
----------
|
____|_____
|Address |
----------

The above relationship corresponds into the following Class Diagram, which indicates that a given Person has a single Address associated.
 
----------------
|Person |
|----------------|
|id:long |
|name:String |
|address:Address |
----------------

----------------
|Address |
|----------------|
|line1:String |
|line2:String |
|city:String |
|state:String |
|zipCode:String |
----------------
However, we will store both the above entities in a single table. And the database structure is as follows,
 CREATE TABLE PERSON (
person_id INTEGER NOT NULL,
name VARCHAR(50),
line1 VARCHAR(50),
line2 VARCHAR(50),
city VARCHAR(25),
state VARCHAR(25),
zip-code VARCHAR(25),
);
Lets look at the Hibernate mapping that involves in mapping both the entities into a single table.
 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.fazlan.Person" table="PERSON">
<id name="id" column="person_id">
<generator class="increment" />
</id>
<property name="name"/>
<component name="address" class="org.fazlan.Address">
<proeprty name="line1" />
<proeprty name="line2" />
<proeprty name="city" />
<proeprty name="state" />
<proeprty name="zipCode" column="zip-code"/>
</component>
</class>
</hibernate-mapping>


That's all about it!

No comments:

Post a Comment