Hibernate




Many to One Mapping

Many To One mapping to represent a many to one relationship between tables. A many to one relationship occurs when many records from the main table correspond to only one record from the second table.

For example, many students can attend to the same course, so many records from the student table will correspond to the same record from the course table.


MANY-TO-ONE-MAPPING


Tools and Technologies Used:

1. Java 8

2. MySQL 8

3. Eclipse IDE

4. mysql-connector-java-8.0.23.jar

5. Hibernate 5.5.7.Final

6. Maven 3.6.1


Maven Project for Many to One Mapping

We need to follow below steps:

Step 1: Click on File --> New --> Maven Project.

HIBERNATE-MANY-TO-ONE-MAPPING-CREATE-MAVEN-PROJECT

Step 2: Check Checkbox Create a simple project (skip archetype selection). Click on Next button.

HIBERNATE-MANY-TO-ONE-MAPPING-CREATE-MAVEN-PROJECT

Step 3: Enter Group Id, Artifact Id, Version, Packaging, Name, Description details and click on Finish button.

HIBERNATE-MANY-TO-ONE-MAPPING-CREATE-MAVEN-PROJECT

Update pom.xml file.

Open pom.xml file and paste below pom.xml file code.

pom.xml


	<project xmlns="http://maven.apache.org/POM/4.0.0"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
		<modelVersion>4.0.0</modelVersion>
		<groupId>com.hareeshsoni.blog.hibernate.mapping</groupId>
		<artifactId>HibernateManyToOneExample</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<name>HibernateManyToOneExample</name>
		<description>Hibernate Many To One Example</description>
		<dependencies>
			<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
			<dependency>
				<groupId>org.hibernate</groupId>
				<artifactId>hibernate-core</artifactId>
				<version>5.5.7.Final</version>
			</dependency>
	
			<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
			<dependency>
				<groupId>mysql</groupId>
				<artifactId>mysql-connector-java</artifactId>
				<version>8.0.23</version>
			</dependency>
	
		</dependencies>
		<build>
			<finalName></finalName>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>3.6.1</version>
					<configuration>
						<source>1.8</source>
						<target>1.8</target>
					</configuration>
				</plugin>
			</plugins>
		</build>
	</project>
		

Update Maven Project

Step 1: Right-click on project HibernateManyToOneExample --> Maven --> Update Project…

HIBERNATE-MANY-TO-ONE-MAPPING-UPDATE-MAVEN-PROJECT

Step 2: Check Checkbox Force Update of Snapshots/Releases. Click on OK Button.

HIBERNATE-MANY-TO-ONE-MAPPING-UPDATE-MAVEN-PROJECT

Project Structure

MANY-TO-ONE-MAPPING


We have used the below JPA Annotations:

@Entity: @Entity annotation specifies that the class is an entity.

@Table: @Table annotation specifies the primary table for the annotated entity.

@Id: @Id annotation marks the particular field as the primary key of the Entity.

@GeneratedValue: This annotation is used to specify how the primary key should be generated.

@Column: This annotation maps the corresponding fields to their respective columns in the database table.

@JoinColumn: This annotation defines the foreign key. It is the column that associates the two tables.

@ManyToOne: This annotation is used to create many to one relationship between Student and Course entities.

Course.java


	package com.hareeshsoni.blog.hibernate.mapping.model;
	
	import javax.persistence.Column;
	import javax.persistence.Entity;
	import javax.persistence.GeneratedValue;
	import javax.persistence.GenerationType;
	import javax.persistence.Id;
	import javax.persistence.Table;
	
	@Entity
	@Table(name = "course")
	public class Course {
	
		@Id
		@GeneratedValue(strategy = GenerationType.IDENTITY)
		@Column(name = "course_id")
		private int courseId;
	
		@Column(name = "course_name")
		private String courseName;
	
		public Course() {
		}
	
		public Course(String courseName) {
			this.courseName = courseName;
		}
	
		public int getCourseId() {
			return courseId;
		}
	
		public void setCourseId(int courseId) {
			this.courseId = courseId;
		}
	
		public String getCourseName() {
			return courseName;
		}
	
		public void setCourseName(String courseName) {
			this.courseName = courseName;
		}
	}


Student.java


	package com.hareeshsoni.blog.hibernate.mapping.model;
	
	import javax.persistence.CascadeType;
	import javax.persistence.Column;
	import javax.persistence.Entity;
	import javax.persistence.GeneratedValue;
	import javax.persistence.GenerationType;
	import javax.persistence.Id;
	import javax.persistence.JoinColumn;
	import javax.persistence.ManyToOne;
	import javax.persistence.Table;
	
	@Entity
	@Table(name = "student")
	public class Student {
		@Id
		@GeneratedValue(strategy = GenerationType.IDENTITY)
		@Column(name = "student_id")
		private int studentId;
	
		@Column(name = "student_name")
		private String studentName;
	
		@ManyToOne(cascade = CascadeType.ALL)
		@JoinColumn(name = "course_id")
		private Course course;
	
		public Student() {
		}
	
		public Student(String studentName) {
			this.studentName = studentName;
		}
	
		public int getStudentId() {
			return studentId;
		}
	
		public void setStudentId(int studentId) {
			this.studentId = studentId;
		}
	
		public String getStudentName() {
			return studentName;
		}
	
		public void setStudentName(String studentName) {
			this.studentName = studentName;
		}
	
		public Course getCourse() {
			return course;
		}
	
		public void setCourse(Course course) {
			this.course = course;
		}
	
	}
	

HibernateUtil.java


	package com.hareeshsoni.blog.hibernate.mapping.util;
	
	import org.hibernate.SessionFactory;
	import org.hibernate.cfg.Configuration;
	
	public class HibernateUtil {
	private static SessionFactory sessionFactory;
		
		private static SessionFactory buildSessionFactory() {
			Configuration configuration = new Configuration();
	    	configuration.configure("hibernate.cfg.xml");
	    	System.out.println("Hibernate configuration file loaded");
	    	SessionFactory sessionFactory = configuration.buildSessionFactory();
	        return sessionFactory;
	    }
		
		public static SessionFactory getSessionFactory() {
			if(sessionFactory == null) 
				sessionFactory = buildSessionFactory();
	        return sessionFactory;
	    }
	}
		

hibernate.cfg.xml

In hibernate.cfg.xml file provide correct username and password.

Create database name "many_to_one_mapping" inside mysql database.


<?xml version='1.0' encoding='utf-8'?>
	<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
	
	<hibernate-configuration>
		<session-factory>
			<!-- Database connection settings -->
			<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
			<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/many_to_one_mapping</property>
			<property name="hibernate.connection.username">root</property>
			<property name="hibernate.connection.password">########</property>
			<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
			<property name="show_sql">true</property>
			<property name="hbm2ddl.auto">update</property>
			<mapping class="com.hareeshsoni.blog.hibernate.mapping.model.Student" />
			<mapping class="com.hareeshsoni.blog.hibernate.mapping.model.Course" />
		</session-factory>
	</hibernate-configuration>
			

MainApp.java

  
	package com.hareeshsoni.blog.hibernate.mapping;
	
	import org.hibernate.Session;
	import org.hibernate.SessionFactory;
	
	import com.hareeshsoni.blog.hibernate.mapping.model.Course;
	import com.hareeshsoni.blog.hibernate.mapping.model.Student;
	import com.hareeshsoni.blog.hibernate.mapping.util.HibernateUtil;
	
	public class MainApp {
	
		public static void main(String[] args) {
	
			SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
			Session session = sessionFactory.openSession();
			session.beginTransaction();
	
			Student student1 = new Student("Mohan");
			Student student2 = new Student("Sohan");
			Student student3 = new Student("Ram");
	
			Course course = new Course("Hibernate");
	
			student1.setCourse(course);
			student2.setCourse(course);
			student3.setCourse(course);
	
			session.save(student1);
			session.save(student2);
			session.save(student3);
	
			session.getTransaction().commit();
			session.close();
			sessionFactory.close();
		}
	
	}
	


Now run MainApp.java

MANY-TO-ONE-MAPPING-RUN-MAIN-APP


Output

MANY-TO-ONE-MAPPING-OUTPUT


Database tables:

Student Table

STUDENT-TABLE


Course Table

COURSE-TABLE



Download Project Code: