One To Many unidirectional mapping in JPA

This is an example of how to use One to Many unidirectional 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 unidirectional mapping between two entities.

Employee Class and Phone 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 @OneToMany annotation to define a one-to-many relationship to another entity, Phone class. With the @JoinTable it creates a join table between the two entities, defining the columns to be joined with the @JoinColumn annotation and the name of the join table.

package com.javacodegeeks.snippets.enterprise;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;

public class Employee {
	private Long id;
    private String name;
    private String surname;
    private String title;
    private Date created;
    @JoinTable(name = "EMP_PHONE", joinColumns = @JoinColumn(name = "EMP_ID"), inverseJoinColumns = @JoinColumn(name = "PHONE_ID"))
    private Collection<Phone> phones;
	public Long getId() {
		return id;
	public void setId(Long id) { = id;
	public String getName() {
		return name;
	public void setName(String 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 void addPhone(Phone phone) {
		if (phones==null) {
			phones = new ArrayList<Phone>();
		if (!phones.contains(phone)) {

	public Collection<Phone> getPhones() {
		return phones;
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", surname=" + surname
				+ ", title=" + title + ", phones=" + phones + "]";

package com.javacodegeeks.snippets.enterprise;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

public class Phone {
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;

	private String number;

	private String type;

	public int getId() {
		return id;

	public void setId(int id) { = id;

	public String getNumber() {
		return number;

	public void setNumber(String phoneNo) {
		this.number = phoneNo;

	public String getType() {
		return type;

	public void setType(String phoneType) {
		this.type = phoneType;

	public String toString() {
		return "Phone [id=" + id + ", number=" + number + ", type=" + type
				+ "]";

The OneToManyUnidirectionalMappingInJPA class

In the OneToManyUnidirectionalMappingInJPA 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 Phone 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 Phone 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 OneToManyUnidirectionalMappingInJPA {
	public static void main(String[] args) {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPersistenceUnit");
		EntityManager em = emf.createEntityManager();
		Phone phone1 = new Phone();
		Phone phone2 = new Phone();
		Employee employee = new Employee();
		employee.setTitle("QA Engineer");
		employee.setCreated(new Date());
		long employeeId = employee.getId();
		Employee dbEmployee =em.find(Employee.class, employeeId);
		System.out.println("dbEmployee " + dbEmployee);




<persistence xmlns=""
	<persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
			<property name="" 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" />


dbEmployee Employee [id=2, name=Jack, surname=Thomson, title=QA Engineer, phones=[Phone id: 1, no: 55555, type: fixed, Phone id: 2, no: 111-111, type: mobile]]

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

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button