Hibernate Component Mapping

A component is a contained object which is persisted as a value, not as an entity.

To implement the same we need to use <component> element in the mapping file.

And will have one single table to keep the value of varaiables of contained object.

Example:

Suppose we have one table: Employee with columns-id,fname,lname,age,sex.

And we will have one entity with name Employee and another with name as Name.

    package com.javasafari;  
      
    public class Name {  
    private String fname,lname;  
      
    //getters and setters  
    }  

    package com.javasafari;  
      
    public class Employee {  
    private int id;  
    private Name name;
    private int age;
    private String sex;  

    //getters and setters  
    }  

Here name is a dependent contained object.

Mapping file will look like:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <component name="name" class="Name">
         <property name="fname" column="first_name" type="string"/>
         <property name="lname" column="last_name" type="string"/>
      </component>
      <property name="age" column="age" type="int"/>
      <property name="sex" column="sex" type="string"/>
   </class>
</hibernate-mapping>

To save as Employee object:

  Session s=new Configuration().configure("hibernate.cfg.xml")
                      .buildSessionFactory().openSession();

	Transaction t=s.beginTransaction();
	t.begin();
	
	Employee e1=new Employee(new Name("Ankit","Adlakha"),26,Male);
	s.save(e1);
	t.commit();
	s.close();