Hibernate JPA One To Many Relation Mapping Example

Project Structure

Now project structure looks like following

JPA One To Many Mapping Example

Just execute below class and see the output

JPAOneToManyExample.java

package com.jpa.onetomany;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.EntityManager;

public class JPAOneToManyExample {

   
public static void main(String[] args) {
       
EntityManager entityManager = EntityManagerUtil.getEntityManager();
       
try {
           
entityManager.getTransaction().begin();
           
            Company company =
new Company();
            company.setCity
("Kolkata");
            company.setCountry
("India");
            company.setState
("Bengal");
            company.setStreet
("Number 15");
            Employee employee1 =
new Employee("Rockey");
            Employee employee2 =
new Employee("Jose");
            Set<Employee> employees =
new HashSet<Employee>();
            employees.add
(employee1);
            employees.add
(employee2);
            company.setEmployees
(employees);
            entityManager.persist
(company);
           
            entityManager.getTransaction
().commit();
       
catch (Exception e) {
           
entityManager.getTransaction().rollback();
       
}finally {
           
entityManager.close();
       
}
    }

}
Output
ADDRESSID CITY COUNTRY STATE STREET
1 Kolkata India Bengal Number 15
EMPLOYEEID EMPLOYEENAME COMPANY_EMPLOYEE
1 Rockey 1
2 Jose 1




Previous 1 2 3








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