Home » Enterprise Java » jpa » Many To One Mapping in JPA

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Many To One Mapping in JPA

In this example we shall show you how to create a many to one 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 many to one mapping between two entities.
 
 
 
 
 
 

ManyToOneMappingInJPA class

In ManyToOneMappingInJPA 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 ManyToOneMappingInJPA {
	
	public static void main(String[] args) {
		
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPersistenceUnit");
		
		EntityManager em = emf.createEntityManager();
		
		em.getTransaction().begin();
		
		Department department = new Department();
		department.setName("HR");
		
		em.persist(department);
		
		Employee employee = new Employee();
		employee.setName("Jack");
		employee.setSurname("Thomson");
		employee.setTitle("QA Engineer");
		employee.setCreated(new Date());
		employee.setDepartment(department);
		
		em.persist(employee);
		
		long employeeId = employee.getId();
		
		em.getTransaction().commit();
		
		em.getTransaction().begin();
		
		Employee dbEmployee =em.find(Employee.class, employeeId);
		System.out.println("dbEmployee " + dbEmployee);
		
		em.getTransaction().commit();
		
		em.close();
	    emf.close();

	}

}

Employee class and Department 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 + ", department=" + department + "]";
	}

}
package com.javacodegeeks.snippets.enterprise;

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

@Entity
public class Department {
	
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;

    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;
    }

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

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=1, name=Jack, surname=Thomson, title=QA Engineer, department=Department [id=1, name=HR]]

 
This was an example of how to create a many to one mapping in JPA.

(No Ratings Yet)
Start the discussion Views Tweet it!

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 our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of