How To Create EntityManagerFactory in JPA

This tutorial explains how to create EntityManagerFactory in your JPA application when you are writing your first JPA programming. It is the standard way of creating the factory if you use the JPA specification. Normally there are two ways to create the factory, one is through the configuration file persistence.xml and another one is through the application server configurations. Here I am going to explain about the first approach how to writing in your programming. You have to follow these steps for creating your EntityManagerFactory.

  1. Create persistence.xml file under the classpath. Make sure that you keep this file under META-INF folder. For example, your source files are maintained in the folder “src”, then create a META-INF folder under “src”.
  2. Another important point is to add the persistence unit name in the configuration file. This one will be used while creating the EntityManagerFactory. Note that each factory will have a name. You can have multiple factories with multiple configuration files. If you are not specifying the unit name, you would get the  javax.persistence.PersistenceException: No Persistence provider for EntityManager named JPAUNIT
  3. Create the factory by passing the persistence unit name as the parameter.
  4. I assume that you have setup the project with all the required files for Java Persistence API (JPA).

Lets see the sample code:


<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="" version="1.0">
    <persistence-unit name="JPAUNIT">
            <property name="connection.jdbc.url" value="jdbc:mysql://localhost:3306/test"/>
            <property name="connection.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="connection.jdbc.user" value="root"/>
            <property name="connection.jdbc.password" value="admin"/>


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

public class HibernateUtil {
    public static void main(String args[]){
    	EntityManagerFactory entityManager = Persistence.createEntityManagerFactory("JPAUNIT");
    	EntityManager entityManager2 = entityManager.createEntityManager();
    	EntityTransaction transaction = entityManager2.getTransaction();
    	Employee employee = new Employee();
    	employee.setEmpName("Senthil Kumar1");;

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!