Home » Enterprise Java » jpa » JPA EntityManager Example

About Chandan Singh

Chandan Singh
Chandan holds a degree in Computer Engineering and is a passionate software programmer. He has good experience in Java/J2EE Web-Application development for Banking and E-Commerce Domains.

JPA EntityManager Example

In this example, we shall try to demonstrate how to use JPA EntityManager. As the name suggests, an EntityManager is a class that manages the state of the Entity(Persist/Update/Delete etc).

Every EntityManager object has an instance of EntityTransaction associated with it. EntityTransaction is used to manage the transactions.

We shall be using Hibernate as the JPA Vendor. The underlying database shall be MySQL.
 
 
 

 
The benefit of using the JPA over any specific ORM related libraries like Hibernate, iBatis is that we need not change the code when we change the vendor. The code is decoupled (or loosely coupled) with the underlying ORM framework.

Let’s build a sample application to see how we can avoid using Hibernate specific interfaces and use JPA interfaces instead:

Employee.java:

package com.jcg.pojo;

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

@Entity
@Table(name="employee")
public class Employee
{
		protected Long employeeId;
		
		protected String name;

		@Id
		@Column(name="employee_id")
		@GeneratedValue(strategy=GenerationType.IDENTITY)
		public  Long getEmployeeId()
		{
				return employeeId;
		}

		public  void setEmployeeId(Long employeeId)
		{
				this.employeeId = employeeId;
		}

		@Column(name="employee_name")
		public  String getName()
		{
				return name;
		}

		public  void setName(String name)
		{
				this.name = name;
		}

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

JPADemo.java:

package com.jcg;

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

import com.isg.maps.Employee;


/**
 * @author Chandan Singh
 *
 */
public class JPADemo
{
		public static void main(String[] args)
    {
				EntityManagerFactory emf = Persistence.createEntityManagerFactory("jcg-JPA");
				EntityManager em = emf.createEntityManager();
				
				em.getTransaction().begin();
				Employee employee = new Employee();
				employee.setName("Chandan");
				System.out.println("COMIITING");
				em.persist(employee);
				em.getTransaction().commit();
				
    }
}

persistence.java:

<?xml version="1.0" encoding="UTF-8"?>
<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="jcg-JPA">
        	<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="myusername" />
			<property name="hibernate.connection.password" value="mypwd" />
			<property name="hibernate.connection.url" value="jdbc:mysql://localhost/research_development" />
		</properties>
        </persistence-unit>
</persistence>
  1. We define the connection properties in the persistence.xml.
  2. Then we look up the persistence unit from the createEntityManagerFactory method of Persistence class of JPA. This returns an object of EntityManagerFactory.
  3. Finally, we can get the EntityManager object from the EntityManagerFactory class.
  4. We ,now, use the EntityManager object to perform CRUD operation on the Entities under the scope of an EntityTransaction object.
  5. The last step is to commit the transaction back tot the database.
TIP:
It is mandatory to place persistence.xml in the META-INF folder.

Conclusion:

Thus we studied about the JPA EntityManager and how we can use it to avoid dependency on any particular ORM Framework.

Download
You can download the source code of this example here: JPAEntityManager.zip
(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