Hibernate JPA Many To Many Relation Mapping Example

Project Structure

Now project structure looks like following

JPA Many To Many Mapping Example

Just execute below class and see the output

JPAManyToManyExample.java

package com.jpa.manytomany;

import javax.persistence.EntityManager;

public class JPAManyToManyExample {

   
public static void main(String[] args) {
       
EntityManager entityManager = EntityManagerUtil.getEntityManager();
       
try {
           
entityManager.getTransaction().begin();
           
            Event event1 =
new Event("Quaterly Sales meeting");
            Event event2 =
new Event("Weekly Status meeting");
           
            Employee employee1 =
new Employee("Rockey");
            Employee employee2 =
new Employee("Jose");
           
            employee1.getEvents
().add(event1);
            employee1.getEvents
().add(event2);
           
            employee2.getEvents
().add(event1);
            employee2.getEvents
().add(event2);
           
            entityManager.persist
(employee1);
            entityManager.persist
(employee2);
           
            entityManager.getTransaction
().commit();
       
catch (Exception e) {
           
entityManager.getTransaction().rollback();
       
}finally {
           
entityManager.close();
       
}
    }

}
Output
EMPLOYEEID EMPLOYEENAME
1 Rockey
2 Jose
EMPLOYEEID EVENTID
1 1
2 1
1 2
2 2
EVENTID EVENTNAME
1 Weekly Status meeting
2 Quaterly Sales meeting




Previous 1 2 3








Your email address will not be published. Required fields are marked *