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.


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"

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

To save as Employee object:

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

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