Hibernate JPA One To One Relation Mapping Example

Project Structure

Now project structure looks like following

JPA One To One Mapping Example

Just execute below class and see the output

JPAOneToOneExample.java

package com.jpa.onetoone;

import javax.persistence.EntityManager;

public class JPAOneToOneExample {

   
public static void main(String[] args) {
       
EntityManager entityManager = EntityManagerUtil.getEntityManager();
       
try {
           
entityManager.getTransaction().begin();
           
            Address address1 =
new Address("Padma Junction", "Cochin",
                   
"Kerala", "India");
            Address address2 =
new Address("Eden Road", "Kolkota", "Bengal",
                   
"India");
            Employee employee1 =
new Employee("Rockey", address1);
            Employee employee2 =
new Employee("Jose", address2);
           
            entityManager.persist
(employee1);
            entityManager.persist
(employee2);
            entityManager.getTransaction
().commit();
       
catch (Exception e) {
           
entityManager.getTransaction().rollback();
       
}finally {
           
entityManager.close();
       
}
    }

}
Output
ADDRESSID CITY COUNTRY STATE STREET
1 Cochin India Kerala Padma Junction
2 Kolkota India Bengal Eden Road
EMPLOYEEID EMPLOYEENAME EMPLOYEE_ADDRESS
1 Rockey 1
2 Jose 2

 





Previous 1 2 3








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