×
☰ See All Chapters

JPA One-to-Many, Many-to-One Bidirectional Association Mapping

Many-To-One mapping is an association between collection of same persistence objects and their related persistence object. Many persistence objects mapped to one related persistence object.

One-to-many mapping is an association between one persistence object holding the collection of same related persistence objects. One persistence object mapped to many persistence objects.

Tables of both the persistence classes will be related in database.

If one persistence object uses other and in back if other using the first persistence object then it becomes bidirectional. If it is bidirectional, then one-to-many bidirectional association mapping and many-to-one bidirectional association mapping both become one and same.

As an example, the association between Employee and Department. Here Employee needs Department information and as well as Department needs Employee information and hence it becomes bidirectional maaping.

JPA One-to-Many, Many-to-One Bidirectional Association Mapping Example

Now let us see how this mapping is done in persistence class by going through an example.  The following code shows how to do one-to-many bidirectional association mapping and many-to-one bidirectional association mapping. We created two entities, Employee and Department. One Employee belongs to one Department but one Department can have many Employee. In Employee class we annotate the Department field with @ManyToOne annotation. In Department class we annotate the collection of Employee by @OneToMany annotation.

Database script (MySQL)

DROP TABLE EMPLOYEE;

COMMIT;

DROP TABLE DEPARTMENT;

COMMIT;

CREATE TABLE DEPARTMENT(

DEPTID INT(5) PRIMARY KEY AUTO_INCREMENT,

DNAME VARCHAR(30)

);

CREATE        TABLE EMPLOYEE(

EMPID INT(5) PRIMARY KEY AUTO_INCREMENT,

ENAME VARCHAR(30),

EMAIL VARCHAR(30),

DEPTID INT(5),

CONSTRAINT FOREIGN KEY (DEPTID) REFERENCES DEPARTMENT (DEPTID)

);

pom.xml

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">

        <modelVersion>4.0.0</modelVersion>

        <groupId>com.java4coding</groupId>

        <artifactId>12M_M21_BidirectionalAssociationMapping</artifactId>

        <packaging>jar</packaging>

        <version>1.0-SNAPSHOT</version>

        <name>12M_M21_BidirectionalAssociationMapping</name>

        <url>https://maven.apache.org</url>

        <dependencies>

                <dependency>

                        <groupId>junit</groupId>

                        <artifactId>junit</artifactId>

                        <version>3.8.1</version>

                        <scope>test</scope>

                </dependency>

                <dependency>

                        <groupId>org.eclipse.persistence</groupId>

                        <artifactId>javax.persistence</artifactId>

                        <version>2.0.0</version>

                </dependency>

                <dependency>

                        <groupId>org.hibernate</groupId>

                        <artifactId>hibernate-entitymanager</artifactId>

                        <version>4.2.8.Final</version>

                </dependency>

                <dependency>

                        <groupId>mysql</groupId>

                        <artifactId>mysql-connector-java</artifactId>

                        <version>8.0.11</version>

                </dependency>

        </dependencies>

</project>

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="https://java.sun.com/xml/ns/persistence"

        xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://java.sun.com/xml/ns/persistence

             https://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"

        version="2.0">

        <persistence-unit name="EmployeePU">

                <provider>org.hibernate.ejb.HibernatePersistence</provider>

                <properties>

                        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/study" />

                        <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver" />

                        <property name="hibernate.connection.username" value="root" />

                        <property name="hibernate.connection.password" value="root" />

                        <property name="hibernate.archive.autodetection" value="class" />

                        <property name="hibernate.show_sql" value="true" />

                        <property name="hibernate.format_sql" value="true" />

                        <property name="hbm2ddl.auto" value="update" />

                </properties>

        </persistence-unit>

</persistence>

Employee.java

package com.java4coding;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.ManyToOne;

import javax.persistence.Table;

@Entity

@Table(name = "EMPLOYEE")

public class Employee {

       

        @Id

        @GeneratedValue(strategy = GenerationType.AUTO)

        @Column(name = "EMPID")

        private int empid;

       

        @Column(name = "ENAME")

        private String ename;

       

        @Column(name = "EMAIL")

        private String email;

       

/*        @Column(name = "DEPTID")

        private int deptid;*/

       

        @ManyToOne

        @JoinColumn(name = "DEPTID")

        private Department department;

        public int getEmpid() {

                return empid;

        }

        public void setEmpid(int empid) {

                this.empid = empid;

        }

        public String getEname() {

                return ename;

        }

        public void setEname(String ename) {

                this.ename = ename;

        }

        public String getEmail() {

                return email;

        }

        public void setEmail(String email) {

                this.email = email;

        }

        public Department getDepartment() {

                return department;

        }

        public void setDepartment(Department department) {

                this.department = department;

        }

}

Department.java

package com.java4coding;

import java.util.HashSet;

import java.util.Set;

import javax.persistence.CascadeType;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.OneToMany;

import javax.persistence.Table;

@Entity

@Table(name = "DEPARTMENT")

public class Department {

       

        @Id

        @GeneratedValue(strategy = GenerationType.AUTO)

        @Column(name = "DEPTID")

        private int deptid;

       

        @Column(name = "DNAME")

        private String dname;

       

        @OneToMany(mappedBy = "department", cascade = CascadeType.ALL)

        private Set<Employee> employees = new HashSet<Employee>(0);

       

        public int getDeptid() {

                return this.deptid;

        }

        public void setDeptid(int deptid) {

                this.deptid = deptid;

        }

        public String getDname() {

                return this.dname;

        }

        public void setDname(String dname) {

                this.dname = dname;

        }

        public Set<Employee> getEmployees() {

                return this.employees;

        }

        public void setEmployees(Set<Employee> employees) {

                this.employees = employees;

        }

}

Test.java

package com.java4coding;

import java.util.HashSet;

import java.util.Set;

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

public class Test {

        public static void main(String[] args) {

                EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeePU");

                EntityManager em = emf.createEntityManager();

                em.getTransaction().begin();

                Department dept = new Department();

                dept.setDname("Engineering");

               

                Employee emp1 = new Employee();

                emp1.setEname("Manu Manjunatha");

                emp1.setEmail("manu.m@java4coding.com");

                //ASSOCIATE DEPARTMENT WITH EMPLOYEE

                emp1.setDepartment(dept);

               

                Employee emp2 = new Employee();

                emp2.setEname("Advith");

                emp2.setEmail("advith@java4coding.com");

                //ASSOCIATE DEPARTMENT WITH EMPLOYEE

                emp2.setDepartment(dept);

               

                Employee emp3 = new Employee();

                emp3.setEname("Likitha Tyagraj");

                emp3.setEmail("likitha@java4coding.com");

                //ASSOCIATE DEPARTMENT WITH EMPLOYEE

                emp3.setDepartment(dept);

               

                Set<Employee> s = new HashSet<>();

                s.add(emp1);

                s.add(emp2);

                s.add(emp3);

               

                //ASSOCIATE EMPLOYEES WITH DEPARTMENT

                dept.setEmployees(s);

                em.persist(dept);

                em.getTransaction().commit();

               

               

                em.getTransaction().begin();

                // DEPARTMENT CAN ACCESS EMPLOYEE

                Department d = em.find(Department.class, 1);

                System.out.println("Department id is " + d.getDeptid());

                System.out.println("Department name is " + d.getDname());

               

               

                Set<Employee> e = d.getEmployees();

               

                for (Employee emp : e) {

                        System.out.println("employee id is " + emp.getEmpid());

                        System.out.println("employee name is " + emp.getEname());

                        System.out.println("employee email is " + emp.getEmail());

                }

       

                // EMPLOYEE CAN ACCESS DEPARTMENT BECAUSE IT IS BIDRECTIONAL

                Employee emp = em.find(Employee.class, 2);

                System.out.println("Employee id is " + emp.getEmpid());

                System.out.println("Employee name is " + emp.getEname());

                System.out.println("Employee email is " + emp.getEmail());

               

                System.out.println("Employee Department is "+emp.getDepartment().getDeptid());

                System.out.println("Employee Department is "+emp.getDepartment().getDname());

               

                em.getTransaction().commit();

        }

}

Project directory structure

jpa-one-to-many-many-to-one-bidirectional-association-mapping-0

Output

Hibernate:

    insert

    into

        DEPARTMENT

        (DNAME)

    values

        (?)

Hibernate:

    insert

    into

        EMPLOYEE

        (DEPTID, EMAIL, ENAME)

    values

        (?, ?, ?)

Hibernate:

    insert

    into

        EMPLOYEE

        (DEPTID, EMAIL, ENAME)

    values

        (?, ?, ?)

Hibernate:

    insert

    into

        EMPLOYEE

        (DEPTID, EMAIL, ENAME)

    values

        (?, ?, ?)

Department id is 1

Department name is Engineering

employee id is 1

employee name is Advith

employee email is advith@java4coding.com

employee id is 2

employee name is Likitha Tyagraj

employee email is likitha@java4coding.com

employee id is 3

employee name is Manu Manjunatha

employee email is manu.m@java4coding.com

Employee id is 2

Employee name is Likitha Tyagraj

Employee email is likitha@java4coding.com

Employee Department is 1

Employee Department is Engineering


All Chapters
Author