Open In App

JPA Many-To-One Mapping

Last Updated : 23 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, JPA is defined as Java Persistence API(JPA), Many-to-one is the common association relationship where the many instances of the entity are associated with one instance of another entity.

Understanding of Many-to-One Mapping in JPA

Many-to-one mapping can establish the relationship between the two entities where the multiple instances of the one entity are associated with the single instance of the other entity. Let’s illustrate the example of the Student entity having a many-to-one relationship with the University entity.

Step-by-Step Implementation

1. Define the Entities:

We can create the two entity classes Student and University and it can establish the many-to-one relationship between them using the annotations.

Student Entity:

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

@ManyToOne
private University university;

// Constructors, getters, and setters
}

University Entity:

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

// Constructors, getters, and setters
}

2. Implement the Mapping:

We can use the appropriate annotations to define the mapping between entities and it can annotate the University field in the Student entity with the @ManyToOne of the application.

@ManyToOne
private University university;

3. Handle the Foreign Key:

We can ensure that the foreign key referencing the primary key of the owning entity is the present in reference entity of the JPA application.

4. Test the Mapping:

We can persist the instances of the entities and retrieve them to the verify the mapping.

Subtopics:

Cascading operations:

JPA can supports the cascading operations where the operations can performed on the one entity can cascade to the associated entities. For the Many-To-One mapping, cascading can be used to the propagate the changes to associated with the entities.

Lazy vs. Eager Loading:

JPA can allows the configuring fetching strategies for the associated with the entities. Lazy loading can fetches the associated with the entities when accessed, while the eager loading fetches them immediately along with owning entity.

Bidirectional Mapping:

Establishing the bidirectional relationships allows the navigation from both sides of the association. In the Many-To-One mapping, bidirectional mapping can involves the defining of the One-To-Many relationship in the owning entity.

Project to Implementation of Many-to-One Mapping in JPA

We can develop the simple JPA project that can Student entity, University entity mapped both of the entities that can save the JPA Many-To-One mapping into the MYSQL database.

Step 1: Create the new JPA project using the IntelliJ Idea named jpa-many-to-one-mapping-demo. After creating the project, the file structure looks like the below image.

onemanyfile


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

 <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>


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="PU_NAME">
        <class>model.Student</class>
        <class>model.University</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 Java package named as the model in that package create the Java class named as the Student. Go to src > main > java > model > Student and put the below code.

Java
package model;

import jakarta.persistence.*;

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

    @ManyToOne
    private University university;

    // 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 University getUniversity() {
        return university;
    }

    public void setUniversity(University university) {
        this.university = university;
    }
}


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

Java
package model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

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

    // 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;
    }
}


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

Java
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import model.Student;
import model.University;

public class MainApplication {
    public static void main(String[] args) {
    // Create EntityManagerFactory
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("PU_NAME");
    EntityManager em = emf.createEntityManager();

    // Begin transaction
        em.getTransaction().begin();

    // Create a university
    University university = new University();
        university.setName("Geek University");
        em.persist(university);

    // Create students
    Student student1 = new Student();
        student1.setName("Mahesh");
        student1.setUniversity(university);
        em.persist(student1);

    Student student2 = new Student();
        student2.setName("Eswar");
        student2.setUniversity(university);
        em.persist(student2);

    // Commit transaction
        em.getTransaction().commit();

    // Retrieve student and university
    Student retrievedStudent = em.find(Student.class, student1.getId());
    University retrievedUniversity = retrievedStudent.getUniversity();

        System.out.println("Student: " + retrievedStudent.getName());
        System.out.println("University: " + retrievedUniversity.getName());

    // Close EntityManager
        em.close();
        emf.close();
}
}


pom.xml:

Below is the XML file after adding all dependencies at the time of project creation.

XML
<?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-many-to-one-mapping-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>jpa-many-to-one-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 7: Once the project is completed, run the application, it will show the student and university as output. Refer the below output image for the better understanding of the concept.

Output in Console

Conclusion

Many-To-One mapping in the JPA allows the establishing the associations between the entities efficiently. By the understanding the concept, We can implementing the mapping. It can efficiently managed the complex relationships into the JPA applications. Developer can gain the solid understanding of the Many-To-One mapping in the JPA application.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads