Hibernate Many-to-One mapping

Many-to-One relationship in real world:

Two items are said to be in Many-to-One relationship if one item is belong to the many occurrences of other item. E.g. Many employees – one department.

Many-to-One relationship in programming:

Two entities are said to be in Many-to-One relationship if one entity belongs to many occurrence of other entity.
Note: One-to-Many and Many-to-One are both same it depends upon the side of entities in the relationship. As one department – many employees refers to the One-to-Many and Many employees – one department refers to the Many-to-One.

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"/>
        <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.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"/>
 
  <many-to-one name="studentClass" column="Student_Class"
    class="com.w3schools.business.StudentClass" 
        cascade="all">
  </many-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.w3schools.business.StudentClass" 
                                                  table="StuClass">
 
		<id name="classId" column="Class_Id" type="string">
			<generator class="native"></generator>
		</id>
		<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 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("MCA1");
 
		//Create the student object.
		Student student1 = new Student("Sandy", "Sethi", 
				 "MCA/07/19", 27, studentClass);
		Student student2 = new Student("Munish", "Mehta", 
				 "MCA/07/04", 27, studentClass);
 
		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.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: select hibernate_sequence.nextval from dual
Hibernate: insert into StuClass (Class_Name, Class_Id) values (?, ?)
Hibernate: insert into Student (First_Name, Last_Name, RollNo, 
Age, Student_Class, Student_Id) values (?, ?, ?, ?, ?, ?)
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Student (First_Name, Last_Name, RollNo, 
Age, Student_Class, Student_Id) values (?, ?, ?, ?, ?, ?)
Hibernate: update StuClass set Class_Name=? where Class_Id=?
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_.Student_Class as Student6_0_ from Student student0_
First Name: Sandy
Last Name: Sethi
RollNo: MCA/07/19
Age: 27
Hibernate: select studentcla0_.Class_Id as Class1_1_0_, 
studentcla0_.Class_Name as Class2_1_0_ from StuClass 
studentcla0_ where studentcla0_.Class_Id=?
Class Name:MCA1
Class Id:240
First Name: Munish
Last Name: Mehta
RollNo: MCA/07/04
Age: 27
Class Name:MCA1
Class Id:240

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