JPA - @OneToMany Relationships



Overview

In this relationship each row of one entity is referenced to many child records in other entity. The important thing is that child records cannot have multiple parents. In a one-to-many relationship between Table A and Table B, each row in Table A is linked to 0, 1 or many rows in Table B.

Let us consider the example if Employee and Department is in a reverse unidirectional manner, relation is Many-To-One relation.

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 java.util.List;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;

@Entity
public class Department {

    @Id 
    @GeneratedValue( strategy=GenerationType.AUTO )
    
    private int id;
    private String name;
    
    @OneToMany( targetEntity=Employee.class )
    private List employeelist;

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

    public List getEmployeelist() {
      return employeelist;
    }

   public void setEmployeelist(List employeelist) {
      this.employeelist = employeelist;
   }
}

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;

@Entity
public class Employee {

   @Id
   @GeneratedValue( strategy= GenerationType.AUTO ) 	

   private int eid;
   private String ename;
   private double salary;
   private String deg;

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

Persistence.xml

Persistence.xml will be created by the eclipse IDE while creating a JPA Project. 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 OneToMany.java is created under given package. The DAO class is shown as follows:

OneToMany.java

package com.tutorialspoint.eclipselink.service;

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

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 OneToMany {
   public static void main(String[] args) {
   
   EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
   EntityManager entitymanager = emfactory.createEntityManager( );
   entitymanager.getTransaction( ).begin( );

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

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

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

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

   //Create Employeelist
   List<Employee> emplist = new ArrayList();
   emplist.add(employee1);
   emplist.add(employee2);
   emplist.add(employee3);

   //Create Department Entity
   Department department = new Department();
   department.setName("Development");
   department.setEmployeelist(emplist);

   //Store Department
   entitymanager.persist(department);

   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 as follows. In this project three tables are created.

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

Select * from department_employee;

Department_Id	Employee_Eid
254	        251
254	        252
254	        253

In the above table, deparment_id and employee_id fields are the foreign keys (reference fields) from department and employee tables.

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
254	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
251	Technical Writer	Satish	       45000
252	Technical Writer	Krishna	       45000
253	Technical Writer	Masthanvali    50000
Advertisements