Ilias Tsagklis

About Ilias Tsagklis

Ilias Tsagklis is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services. Ilias is co-founder and Executive Editor at Java Code Geeks.

One To Many bidirectional mapping in JPA

With this example we are going to demonstrate how to use One to Many bidirectional mapping in JPA. The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications.

Here, we are using the JPA to define a one to many bidirectional mapping between two entities.

The Employee class

The Employee class is an entity class, annotated with the javax.persistence.Entity annotation. It uses the @Id annotation to define its id property, and the @GeneratedValue annotation with strategy set to GenerationType.AUTO so that the id gets auto-generated values. In another property, it uses the @ManyToOne annotation to define a many-to-one relationship to another entity, that is Department class.

package com.javacodegeeks.snippets.enterprise;

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class Employee {
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private Long id;
    private String name;
    private String surname;
    private String title;
    private Date created;
    @ManyToOne
    private Department department;
    
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String getSurname() {
		return surname;
	}
	public void setSurname(String surname) {
		this.surname = surname;
	}
	
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	
	public Date getCreated() {
		return created;
	}
	public void setCreated(Date created) {
		this.created = created;
	}
	
	public Department getDepartment() {

  return department;
    }
    
    public void setDepartment(Department department) {
  this.department = department;
    }
	
	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", surname=" + surname
				+ ", title=" + title + "]";
	}
}

The Department class

The Department class is also an entity class, annotated with the javax.persistence.Entity annotation. It also uses the @Id annotation to define its id property, and the @GeneratedValue annotation with strategy set to GenerationType.AUTO so that the id gets auto-generated values. In another property, it uses the @OneToMany annotation to define a one-to-many relationship to another entity, that is Employee class. The relationship is owned by the employee field in the Department entity, as defined in the annotation.

package com.javacodegeeks.snippets.enterprise;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Department {
	
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    @OneToMany(mappedBy="employee")
    private Collection employees;

    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 void addEmployee(Employee employee) {
  if (!employees.contains(employee)) {
  	employees.add(employee);

  }
    }

	public Collection getEmployees() {
		return employees;
	}

	@Override
	public String toString() {
		return "Department [employees=" + employees + ", id=" + id + ", name="
				+ name + "]";
	}  
}

The OneToManyBidirectionalMappingInJPA class

In the OneToManyBidirectionalMappingInJPA class we create an EntityManagerFactory interface to interact with the entity manager factory for MyPeristenceUnit, that is defined in persistence.xml file. We create an EntityManager, using the createEntityManager() API method. Then, we create new Employee and Department objects. The new objects are written to the database, using the persist(java.lang.Object entity) API method of EntityManager. The getTransaction().begin() and getTransaction().commit() methods are used before and after the EntityManager invokes a method so that a transaction begins and ends. The Employee and Department objects can be retrieved using the find(java.lang.Class<T> entityClass, java.lang.Object primaryKey) API method of EntityManager.

package com.javacodegeeks.snippets.enterprise;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class OneToManyBidirectionalMappingInJPA {
	
	public static void main(String[] args) {
		
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPersistenceUnit");
		
		EntityManager em = emf.createEntityManager();
		
		em.getTransaction().begin();
		
		Department department1 = new Department();
		department1.setName("Q/A");

		Department department2 = new Department();
		department2.setName("HR");
		
		Employee employee1 = new Employee();
		employee1.setName("Jack");
		employee1.setSurname("Thomson");
		employee1.setTitle("QA Engineer");
		employee1.setCreated(new Date());
		employee1.setDepartment(department1);

		Employee employee2 = new Employee();
		employee2.setName("Mary");
		employee2.setSurname("Nickolson");
		employee2.setTitle("QA Engineer");
		employee2.setCreated(new Date());
		employee2.setDepartment(department2);
		
		em.persist(department1);
		em.persist(department2);
		em.persist(employee1);
		em.persist(employee2);
		
		long employeeId1 = employee1.getId();
		long employeeId2 = employee2.getId();
		
		em.getTransaction().commit();
		
		em.getTransaction().begin();
		
		Employee dbEmployee1 =em.find(Employee.class, employeeId1);
		System.out.println("dbEmployee " + dbEmployee1);
		
		Employee dbEmployee2 =em.find(Employee.class, employeeId2);
		System.out.println("dbEmployee " + dbEmployee2);
		
		em.getTransaction().commit();
		
		em.close();
	    emf.close();

	}

}

persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
	
	<persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<properties>
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
			<property name="hibernate.hbm2ddl.auto" value="update" />
			<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
			<property name="hibernate.connection.username" value="jcg" />
			<property name="hibernate.connection.password" value="jcg" />
			<property name="hibernate.connection.url" value="jdbc:mysql://localhost/companydb" />
		</properties>
	</persistence-unit>
	
</persistence>

Output:

dbEmployee Employee [id=3, name=Jack, surname=Thomson, title=QA Engineer, phones=null]
dbEmployee Employee [id=4, name=Mary, surname=Nickolson, title=QA Engineer, phones=null]

 
This was an example of how to use One to Many bidirectional mapping in JPA.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close