VOOZH about

URL: https://www.geeksforgeeks.org/java/hibernate-many-to-one-mapping/

⇱ Hibernate - Many-to-One Mapping - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Hibernate - Many-to-One Mapping

Last Updated : 26 Aug, 2025

In relational databases, a Many-to-One relationship occurs when multiple records in one table are associated with a single record in another table.

For example, in a workplace scenario:

  • Many employees work in the same company.
  • Each employee is linked to a single company address.

This type of relationship helps to avoid data redundancy and maintain consistency.

Syntax:

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Foreign key column")

Step-by-Step Implementation

Step 1: Create a Spring Boot project using STS

Create a project using STS and enter project details in the New Spring Starter Project window:

  • Name / Artifact: GFG-MAPPING-PROJECT
  • Group / Package: com.gfg
  • Type: Maven Project
  • Packaging: Jar
  • Java Version: 8
  • Description: Demo project for Hibernate Mapping

Click Next to select Spring Boot version and dependencies (Spring Data JPA, MySQL Driver), then click Finish.

👁 Project Structure
Dependencies

Step 2: Configure application.properties

Go to src/main/resources open application.properties in that adding the necessary properties as below

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/schemaname

spring.datasource.username=root

spring.datasource.password=password

spring.jpa.show-sql=true

spring.jpa.hibernate.ddl-auto=update

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

Step 3: Create Model Classes

Go to src/main/java create a package for model classes(ex : com.gfg.model) and create one package for repository  (ex :com.gfg.repository). Then create two model classes under the model package

  • Employee.java
  • Address.java

Employee.java

Address.java

Step 4: Create Repository Interfaces

Go to repository package adding the JPA repository of both model  classes 

EmployeeRepo.java


AddressRepo.java

Step 5: Main Application & Data Insertion

Go to starter class Autowire two repository interfaces and create objects for model classes 

GfgMappingProjectApplication.java

Step 6: Run Application & Verify

  • Right-click GfgMappingProjectApplication -> Run as Spring Boot Application
👁 Output
Run Application & Verify

Then go to Database then check for tables. 

Address Table:

select * from address;

👁 Output
Address Table

Employee Table:

select * from employee;

👁 Output
Employee Table
  • One address record in address table
  • Two employee records linked to that address in employee table
Comment
Article Tags:
Article Tags: