JPA - @ManyToOne Relationships



Overview

Many-To-One relation between entities − Where one entity (column or set of columns) is/are referenced with another entity (column or set of columns) which contain unique values. In relational databases these relations are applicable by using foreign key/primary key between tables.

Let us consider an example of relation between Employee and Department entities. In unidirectional manner, i.e.from Employee to Department, Many-To-One relation is applicable. That means each record of employee contains one department id, which should be a primary key in Department table. Here in the Employee table, Department id is foreign Key.

The diagram explains Many-To-One relation as follows:

@ManyToOne Relation

Creating Entities

Follow the above given diagram for creating entities. Create a package named com.tutorialspoin.eclipselink.entity under src package if not present. Create a class named Department.java under given package. The class Department entity is shown as follows:

Department.java

package com.tutorialspoint.eclipselink.entity;

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

@Entity
public class Department {

   @Id 
   @GeneratedValue( strategy=GenerationType.AUTO )

   private int id;
   private String name;

   public int getId() {
      return id;
   }

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

   public String getName( ){
      return name;
   }

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

Create the second entity in this relation - Employee entity class named Employee.java under com.tutorialspoint.eclipselink.entity package. The Employee entity class is shown as follows:

Employee.java

package com.tutorialspoint.eclipselink.entity;

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

@Entity
public class Employee{

   @Id
   @GeneratedValue( strategy= GenerationType.AUTO ) 	
   
   private int eid;
   private String ename;
   private double salary;
   private String deg;
   
   @ManyToOne
   private Department department;

   public Employee(int eid, String ename, double salary, String deg) {
      super( );
      this.eid = eid;
      this.ename = ename;
      this.salary = salary;
      this.deg = deg;
   }

   public Employee( ) {
      super();
   }

   public int getEid( ) {
      return eid;
   }
   
   public void setEid(int eid)  {
      this.eid = eid;
   }

   public String getEname( ) {
      return ename;
   }
   
   public void setEname(String ename) {
      this.ename = ename;
   }

   public double getSalary( ) {
      return salary;
   }
   
   public void setSalary(double salary) {
      this.salary = salary;
   }

   public String getDeg( ) {
      return deg;
   }
   
   public void setDeg(String deg) {
      this.deg = deg;
   }

   public Department getDepartment() {
      return department;
   }

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

Persistence.xml

Persistence.xml file is required to configure the database and the registration of entity classes.

The configuration details are user specifications. The persistence.xml file is shown as follows:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="3.0" 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">
	<persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
	<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
	<class>com.tutorialspoint.eclipselink.entity.Employee</class>
	<class>com.tutorialspoint.eclipselink.entity.Department</class>
      <properties>
         <property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
         <property name="jakarta.persistence.jdbc.user" value="guest"/>
         <property name="jakarta.persistence.jdbc.password" value="guest123"/>
         <property name="jakarta.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
         <property name="eclipselink.logging.level" value="FINE"/>
         <property name="eclipselink.ddl-generation" value="create-tables"/>
      </properties>
	</persistence-unit>
</persistence>

Service Classes

This module contains the service classes, which implements the relational part using the attribute initialization. Create a package under src package named com.tutorialspoint.eclipselink.service. The DAO class named ManyToOne.java is created under given package. The DAO class is shown as follows:

ManyToOne.java

package com.tutorialspoint.eclipselink.service;

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

import com.tutorialspoint.eclipselink.entity.Department;
import com.tutorialspoint.eclipselink.entity.Employee;

public class ManyToOne {
   public static void main( String[ ] args ) {
   
   EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
   EntityManager entitymanager = emfactory.createEntityManager( );
   entitymanager.getTransaction( ).begin( );

   //Create Department Entity
   Department department = new Department();
   department.setName("Development");
   
   //Store Department
   entitymanager.persist(department);

   //Create Employee1 Entity
   Employee employee1 = new Employee();
   employee1.setEname("Satish");
   employee1.setSalary(45000.0);
   employee1.setDeg("Technical Writer");
   employee1.setDepartment(department);

   //Create Employee2 Entity
   Employee employee2 = new Employee();
   employee2.setEname("Krishna");
   employee2.setSalary(45000.0);
   employee2.setDeg("Technical Writer");
   employee2.setDepartment(department);

   //Create Employee3 Entity
   Employee employee3 = new Employee();
   employee3.setEname("Masthanvali");
   employee3.setSalary(50000.0);
   employee3.setDeg("Technical Writer");
   employee3.setDepartment(department);

   //Store Employees
   entitymanager.persist(employee1);
   entitymanager.persist(employee2);
   entitymanager.persist(employee3);

   entitymanager.getTransaction().commit();
   entitymanager.close();
   emfactory.close();
   }
}

Output

After compilation and execution of the above program you will get notifications in the console panel of Eclipse IDE. For output, check MySQL workbench. In this example two tables are created.

Pass the following query in MySQL interface and the result of Department table in a tabular format is shown as follows in the query:

Select * from department;

Id	Name
101	Development

Pass the following query in MySQL interface and the result of Employee table in a tabular format is shown as follows in the query:

Select * from employee;

Eid Deg                 Ename	        Salary	Department_Id
102 Technical Writer	Satish	        45000	101
103 Technical Writer	Krishna	        45000	101
104 Technical Writer	Masthan Wali	50000	101

In the above table Deparment_Id is the foreign key (reference field) from Department table.

Advertisements