jpa

JPA EntityManager Example

Photo of Chandan SinghChandan SinghJanuary 14th, 2015Last Updated: February 27th, 2019
1 662 2 minutes read

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

EveryEntityManager object has an instance ofEntityTransaction associated with it.EntityTransaction is used to manage the transactions.

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

 
The benefit of using theJPA 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 usingHibernate specific interfaces and useJPA 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 thepersistence.xml.
  2. Then we look up the persistence unit from thecreateEntityManagerFactory method ofPersistence class of JPA. This returns an object ofEntityManagerFactory.
  3. Finally, we can get theEntityManager object from theEntityManagerFactory class.
  4. We ,now, use theEntityManager object to performCRUD operation on theEntities under the scope of anEntityTransaction object.
  5. The last step is tocommit thetransaction back tot the database.
TIP:
It is mandatory to placepersistence.xml in theMETA-INF folder.

Conclusion:

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

Want to be a JPA Master ?
Subscribe to our newsletter and download the JPAUltimateGuideright now!
In order to help you master programming with JPA, we have compiled a kick-ass guide with all the major JPA features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

Download
You can download the source code of this example here:JPAEntityManager.zip
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
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 ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Chandan SinghChandan SinghJanuary 14th, 2015Last Updated: February 27th, 2019
1 662 2 minutes read
Photo of 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.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.