Hibernate component mapping

Component Class:

A class is said to be a component class if it is completely depends upon its container class life cycle and it is stored as a member variable not as an instance.

Component mapping:

If an entity class has a reference entity as a component variable then this property can mapped by using <component> element.

Example:

Student.java

/**
 * This class represents a persistent class for Student.
 * @author w3schools
 */
public class Student {
	//data members
	private int studentId;
	private String firstName;
	private String lastName;
	private String rollNo;
	private int age;
	private StudentClass studentClass;
 
	//no-argument constructor
	public Student(){
 
	}
 
	//argument constructor
	public Student(String firstName, String lastName, String 
                        rollNo, int age, StudentClass studentClass){
		this.firstName = firstName;
		this.lastName = lastName;
		this.rollNo = rollNo;
		this.age = age;	
		this.studentClass = studentClass;
	}
 
	//getter and setter methods
	public int getStudentId() {
		return studentId;
	}
	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getRollNo() {
		return rollNo;
	}
	public void setRollNo(String rollNo) {
		this.rollNo = rollNo;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public StudentClass getStudentClass() {
		return studentClass;
	}
	public void setStudentClass(StudentClass studentClass) {
		this.studentClass = studentClass;
	}
 
}

StudentClass.java

/**
 * This class represents a persistent class for Subject.
 * @author w3schools
 */
public class StudentClass {
	//data members
	private String classId;
	private String className;
 
	//no argument constructor
	public StudentClass(){
 
	}
 
	//argument constructor
	public StudentClass(String className){
		this.className = className;
	}
 
	//getter and setter methods
	public String getClassId() {
		return classId;
	}
	public void setClassId(String classId) {
		this.classId = classId;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
}

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
    <session-factory>
        <property name="dialect">
           org.hibernate.dialect.OracleDialect
        </property>
        <property name="connection.url">
           jdbc:oracle:thin:@localhost:1521:XE
        </property>
        <property name="connection.username">
           system
        </property>
        <property name="connection.password">
           oracle
        </property>
        <property name="connection.driver_class">
           oracle.jdbc.driver.OracleDriver
        </property>
        <property name="hbm2ddl.auto">
           update
        </property>
        <property name="show_sql">
           true
        </property>
 
        <mapping resource="student.hbm.xml"/>
 
    </session-factory>
 
</hibernate-configuration>

student.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping SYSTEM
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping>
 
 <class name="com.w3schools.business.Student" table="Student">
  <id name="studentId" type="int" column="Student_Id">
	<generator class="native"></generator>
  </id>
 
  <property name="firstName" column="First_Name" type="string"/>
  <property name="lastName" column="Last_Name" type="string"/>
  <property name="rollNo" column="RollNo" type="string"/>
  <property name="age" column="Age" type="int"/>
 
  <component name="studentClass" 
           class="com.w3schools.business.StudentClass">
    <property name="classId" column="Class_Id" type="string"/>
    <property name="className" column="Class_Name" type="string"/>
  </component>
 
 </class>
 
</hibernate-mapping>

HibernateUtil.java

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
/**
 * This is a utility class for getting the hibernate session object.
 * @author w3schools
 */
public class HibernateUtil {
    private static final SessionFactory sessionFactory = 
                                           buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() {
    	SessionFactory sessionFactory = null;
        try {
        	//Create the configuration object.
        	Configuration configuration = new Configuration(); 
        	//Initialize the configuration object 
                //with the configuration file data
        	configuration.configure("hibernate.cfg.xml");
        	// Get the SessionFactory object from configuration.
        	sessionFactory = configuration.buildSessionFactory();
        }
        catch (Exception e) {
           e.printStackTrace();
        }
        return sessionFactory;
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
 
}

HibernateTest.java

import com.w3schools.persistence.StudentDBOperations;
 
/**
 * This class is used for the hibernate operations.
 * @author w3schools
 */
public class HibernateTest {
	public static void main(String args[]){
		StudentClass studentClass = 
                              new StudentClass("IT1","MCA1");
 
		//Create the student object.
		Student student = new Student("Amani", "kaur", 
				 "MCA/07/14", 27, studentClass);
 
 
		StudentDBOperations obj = new StudentDBOperations();
		//insert student object.
		obj.addStudent(student);
 
		//show all student object.
		obj.showAllStudentDetails();
 
	}
}

StudentDBOperations.java

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.w3schools.business.Student;
import com.w3schools.business.StudentClass;
 
/**
 * This class contains the methods to interact with database.
 * @author w3schools
 */
public class StudentDBOperations {
	/**
	 * This method is used to insert a new student record.
	 * @param student
	 * @return studentId
	 * @author w3schools
	 */
	public Integer addStudent(Student student){
	    Transaction tx = null;
	    Integer studentId = null;
	    //Get the session object.
	    Session session = 
                  HibernateUtil.getSessionFactory().openSession();
	    try{
	         tx = session.beginTransaction();
	         studentId = (Integer) session.save(student); 
	         tx.commit();
	      }catch (HibernateException e) {
	         if(tx!=null){
	        	 tx.rollback();
	         }
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return studentId;	
	}
 
	/**
	 * This method is used retrieve and show the records.
	 * @author w3schools
	 */
	public void showAllStudentDetails(){
	    Transaction tx = null;
	    //Get the session object.
	    Session session = 
                    HibernateUtil.getSessionFactory().openSession();
	    try{
	         tx = session.beginTransaction();
	         List<Student> students = 
                        session.createQuery("FROM Student").list();
	         for(Student student : students){
	        	 System.out.println("First Name: "
                                         + student.getFirstName()); 
	        	 System.out.println("Last Name: " 
                                          + student.getLastName());  
	        	 System.out.println("RollNo: "
                                            + student.getRollNo()); 
	        	 System.out.println("Age: "
                                               + student.getAge()); 
 
	        	 StudentClass studentClass = 
                                         student.getStudentClass();
	        	 System.out.println("Class Name:"
                                    + studentClass.getClassName());
	        	 System.out.println("Class Id:" 
                                     + studentClass.getClassId());
	         }
	         tx.commit();
	      }catch (HibernateException e) {
	         if(tx!=null){
	        	 tx.rollback();
	         }
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	}
}

Output:

Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Student (First_Name, Last_Name, RollNo, 
Age, Class_Id, Class_Name, Student_Id) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: select student0_.Student_Id as Student1_0_, 
student0_.First_Name as First2_0_, student0_.Last_Name as
 Last3_0_, student0_.RollNo as RollNo0_, student0_.Age as 
Age0_, student0_.Class_Id as Class6_0_, student0_.Class_Name
 as Class7_0_ from Student student0_
First Name: Amani
Last Name: kaur
RollNo: MCA/07/14
Age: 27
Class Name:MCA1
Class Id:IT1

Download this example.
 
Next Topic: Hibernate Query Language (HQL) with example.
Previous Topic: Hibernate Many-to-Many mapping using xml with example.

Related Topics:

Hibernate One-to-One Mapping using xml with example.
Hibernate One-to-Many mapping using xml with example.
Hibernate Many-to-One mapping using xml with example.
Hibernate Many-to-Many mapping using xml with example.