How do I create JPA EntityManagerFactory?

In this code snippet you will learn how to create JPA EntityManagerFactory. This factory enable you to create the EntityManager which will be used to execute the JPA command to manipulate the database tables.

To create the EntityManagerFactory you need to create to persistence.xml file first. The file is where you configure the JPA. This file must be placed inside the META-INF directory in your program working directory.

Here is an example of the persistence.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns:xsi=""
             version="2.0" xmlns="">

    <persistence-unit name="music" transaction-type="RESOURCE_LOCAL">
            <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/musicdb" />
            <property name="javax.persistence.jdbc.user" value="music" />
            <property name="javax.persistence.jdbc.password" value="s3cr*t" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="" value="update" />


The persistence unit defined in the persistence.xml file contains a set of entities object. We also define some properties related to the database connections including the JDBC driver class, JDBC url, the username and password for opening the connection to database.

After defining the persistence.xml file we’ll create a simple program to create the EntityManagerFactory. To create the factory we can use the javax.persistence.Persistence class createEntityManagerFactory() method and pass the persistence unit name as the parameter. In this example the persistence unit name is music as can be seen in the persistence.xml file.

After we have the factory object created we can then create an EntityManager by calling the createEntityManager() of the factory object. Let’s see the code snippet below.

package org.kodejava.jpa;

import org.kodejava.jpa.entity.Artist;

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

public class EntityManagerFactoryExample {
    public static final String PERSISTENCE_UNIT_NAME = "music";

    public static void main(String[] args) {
        EntityManagerFactory factory =
        EntityManager manager = factory.createEntityManager();

        // Do something with the entity manager.
        Artist artist = manager.find(Artist.class, 1L);
        System.out.println("artist = " + artist);

The Artist entity class definition.

package org.kodejava.jpa.entity;

import javax.persistence.*;
import java.util.Objects;

@Table(name = "artist")
public class Artist implements Serializable {
    private static final long serialVersionUID = 1L;

    private Long id;
    private String name;

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long getId() {
        return id;

    public void setId(Long id) { = id;

    @Column(name = "name", length = 100, nullable = false)
    public String getName() {
        return name;

    public void setName(String name) { = name;

    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Artist artist = (Artist) o;
        return Objects.equals(id, &&

    public int hashCode() {
        return Objects.hash(id, name);

    public String toString() {
        return "Artist{" +
                "id=" + id +
                ", name='" + name + '\'' +

Our project directory structure.

├─ pom.xml
└─ src
   └─ main
      ├─ java
      │  └─ org
      │     └─ kodejava
      │        └─ jpa
      │           ├─
      │           └─ entity
      │              ├─
      │              ├─
      │              ├─
      │              ├─
      │              ├─
      │              ├─
      │              └─
      └─ resources
         └─ META-INF
            └─ persistence.xml

Maven Dependencies


Maven Central Maven Central Maven Central


Leave a Reply

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