Project to Implement One-to-Many Mapping in JPA

Step 1: Create the new JPA project using the Intellj Idea named as jpa-one-to-many-mapping-demo.

Step 2: Open the open.xml and add the below dependencies into the project.

Dependencies:

<!-- Database Driver (MySQL in this example) -->        
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>

once create the project then the file structure looks like the below image.


Step 3: Open the persistence.xml and put the below code into the project and it can configure the database of the project.

XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"
             version="3.0">
    <persistence-unit name="examplePU">
        <class>model.Student</class>
        <class>model.Employee</class>
        <class>model.Department</class>
        <class>model.Course</class>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/example"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value=""/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>

    </persistence-unit>
</persistence>


Step 4: Create the new Java package named as model in that package create the new Entity Java class named as the Employee. Go to src > main > java > model > Employee and put the below code.

Java
package model;

import jakarta.persistence.*;

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;

    // Constructors, getters, and setters


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }
}


Step 5: create the new Entity Java class named as the Department. Go to src > main > java > model > Department and put the below code.

Java
package model;

import jakarta.persistence.*;

import java.util.ArrayList;
import java.util.List;

@Entity
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Employee> employees = new ArrayList<>(); // Initialize the list here


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }
}


Step 6: Create the new Java class named as the JPAUtil. Go to src > main > java > JPAUtil and put the below code.

Java
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;

public class JpaUtil {
    private static final EntityManagerFactory emFactory;

    static {
        emFactory = Persistence.createEntityManagerFactory("persistence-unit-name");
    }

    public static EntityManager getEntityManager() {
        return emFactory.createEntityManager();
    }

    public static void close() {
        emFactory.close();
    }
}


Step 7: Create the new Java class named as the MainApplication. Go to src > main > java > MainApplication and put the below code.

Java
import jakarta.persistence.EntityManager;
import model.Department;
import model.Employee;

public class MainApplication {
    public static void main(String[] args) {
        // Create entities
        Department department = new Department();
        department.setName("Engineering");

        Employee emp1 = new Employee();
        emp1.setName("Raju");

        Employee emp2 = new Employee();
        emp2.setName("Eswar");

        // Associate employees with the department
        emp1.setDepartment(department);
        emp2.setDepartment(department);

        department.getEmployees().add(emp1);
        department.getEmployees().add(emp2);

        // Persist entities
        EntityManager entityManager = JpaUtil.getEntityManager();
        entityManager.getTransaction().begin();

        entityManager.persist(department);
        entityManager.persist(emp1);
        entityManager.persist(emp2);

        entityManager.getTransaction().commit();

        // Close EntityManager
        entityManager.close();

        // Retrieve and print the persisted data
        entityManager = JpaUtil.getEntityManager();
        Department retrievedDepartment = entityManager.find(Department.class, department.getId());
        System.out.println("Department: " + retrievedDepartment.getName());
        System.out.println("Employees:");
        for (Employee employee : retrievedDepartment.getEmployees()) {
            System.out.println("- " + employee.getName());
        }

        // Close EntityManager
        entityManager.close();

        // Close EntityManagerFactory
        JpaUtil.close();
    }
}


pom.xml

Java
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>jpa-one-to-many-mapping-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>jpa-one-to-many-mapping-demo</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.target>11</maven.compiler.target>
        <maven.compiler.source>11</maven.compiler.source>
        <junit.version>5.9.2</junit.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.0.2.Final</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-runtime</artifactId>
            <version>3.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
        </plugins>
    </build>
</project>


Step 8: Once the project is completed, run the application then show the department and employees with departments as output the products as output. Refer the below image for the better understanding of the concept.

In the above project, Demonstrating the simple JPA application for implementing the one-to-many mapping using the JPA of the project.


JPA – One-to-Many Mapping

In Java Persistence API(JPA), JPA can serve as the fundamental tool for Java developers to interact with databases in an object-oriented manner. Among the many features it can offer One-to-many mapping is the crucial concept that can used to establish the relationships between the entities in the database.

Similar Reads

Understanding the One-to-Many Mapping

One-to-many mapping can represent the relationship where one entity instance is associated with multiple instances of another entity. For instance, consider the scenario where one Department can have multiple Employees. In that case, the Department is the one side and the Employee is the Many side....

Steps to Implement One-to-Many Mapping

1. Define the Entities:...

Project to Implement One-to-Many Mapping in JPA

Step 1: Create the new JPA project using the Intellj Idea named as jpa-one-to-many-mapping-demo....

Conclusion

One-to-many mapping in the JPA can provides the establishment of the relationships between the entities and it can enabling the efficient data management in the Java applications....

Contact Us