Hibernate One-to-One Mapping

One-to-One relationship in real world:

Two items are said to be in One-to-One relationship if one item is only belong to other. E.g. One person has one passport.

One-to-One relationship in hibernate mapping:

Two entities are said to be in One-to-One relationship if one entity has only one occurrence in other entity.

Example:

Student.java

/**
 * This class represents a persistent class for Student.
 * @author w3spoint
 */
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 w3spoint
 */
public class StudentClass {
	//data members
	private String classId;
	private String className;
	private Student student;
	private int studentId;
 
	//no argument constructor
	public StudentClass(){
 
	}
 
	//argument constructor
	public StudentClass(String classId, String className){
		this.classId = classId;
		this.className = className;
	}
 
	public StudentClass(Student student, 
                            String classId, String className){
		this.student = student;
		this.classId = classId;
		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;
	}
	public Student getStudent() {
		return student;
	}
	public void setStudent(Student student) {
		this.student = student;
	}	
	public int getStudentId() {
		return studentId;
	}
	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}
 
}

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"/>
        <mapping resource="StudentClass.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.w3spoint.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"/>
 
  <one-to-one name="studentClass" 
     class="com.w3spoint.business.StudentClass" cascade="all">
  </one-to-one>
 
 </class>
 
</hibernate-mapping>

studentclass.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.w3spoint.business.StudentClass" 
                                                  table="StuClass">
 
		<id name="studentId" type="int" column="Student_Id">
		<generator class="foreign">
			<param name="property">student</param>
		</generator>
		</id>
 
		<one-to-one name="student" 
		   class="com.w3spoint.business.Student" 
                                             constrained="true">
		</one-to-one>
 
		<property name="classId" 
                       column="Class_Id" type="string"></property>
		<property name="className" 
                       column="Class_Name" type="string"></property>
	</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 w3spoint
 */
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.w3spoint.persistence.StudentDBOperations;
 
/**
 * This class is used for the hibernate operations.
 * @author w3spoint
 */
public class HibernateTest {
	public static void main(String args[]){
		StudentClass studentClass1 = 
                               new StudentClass("IT1","MCA1");
		StudentClass studentClass2 = 
                               new StudentClass("IT2","MCA2");
 
		//Create the student object.
		Student student1 = new Student("Amani", "kaur", 
				 "MCA/07/14", 27, studentClass1);
		Student student2 = new Student("Prabhjot", "kaur", 
				 "MCA/07/42", 27, studentClass2);
 
		studentClass1.setStudent(student1);
		studentClass2.setStudent(student2);
 
 
		StudentDBOperations obj = new StudentDBOperations();
		//insert student object.
		obj.addStudent(student1);
		obj.addStudent(student2);
 
		//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.w3spoint.business.Student;
import com.w3spoint.business.StudentClass;
 
/**
 * This class contains the methods to interact with database.
 * @author w3spoint
 */
public class StudentDBOperations {
	/**
	 * This method is used to insert a new student record.
	 * @param student
	 * @return studentId
	 * @author w3spoint
	 */
	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 w3spoint
	 */
	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, Student_Id) values (?, ?, ?, ?, ?)
Hibernate: insert into StuClass (Class_Id, Class_Name, Student_Id)
 values (?, ?, ?)
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Student (First_Name, Last_Name, RollNo, 
Age, Student_Id) values (?, ?, ?, ?, ?)
Hibernate: insert into StuClass (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_ from Student student0_
Hibernate: select studentcla0_.Student_Id as Student1_1_0_,
 studentcla0_.Class_Id as Class2_1_0_, studentcla0_.Class_Name 
as Class3_1_0_ from StuClass studentcla0_ where 
studentcla0_.Student_Id=?
Hibernate: select studentcla0_.Student_Id as Student1_1_0_, 
studentcla0_.Class_Id as Class2_1_0_, studentcla0_.Class_Name 
as Class3_1_0_ from StuClass studentcla0_ where 
studentcla0_.Student_Id=?
First Name: Amani
Last Name: kaur
RollNo: MCA/07/14
Age: 27
Class Name:MCA1
Class Id:IT1
First Name: Prabhjot
Last Name: kaur
RollNo: MCA/07/42
Age: 27
Class Name:MCA2
Class Id:IT2

Download this example.   Next Topic: Hibernate One-to-Many mapping using xml with example. Previous Topic: Hibernate association mappings with example.

 

Please follow and like us:
Content Protection by DMCA.com