JPA persistence.xml Example

Hello readers! In this tutorial we will show how to implement the Java Persistence API and define the JPA Persistence Units with EclipseLink and MySQL in Java.

1. Introduction

Java Persistence API (JPA), is a standard interface which wraps the different Object Relational Mapping (ORM) tools such as Hibernate, EclipseLink, OpenJPA etc. JPA provides a javax.persistence.EntityManager interface which is used to interact with the database. The instance of EntityManager plays around the persistence context and the EntityManagerFactory interacts with the EntityManager object.

  • Persistence Context is the set of entity instances where for any persistence entity identity, there is a unique entity instance. The lifecycle of entity instances is managed within the persistence context using the EntityManager. We can detach and merge the entity instances within a persistence context
  • Entity Manager is a model borrowed from the traditional JDBC frameworks i.e. making it easier for the developers to perform the basic database operations with a very little code

In this standalone JPA example, we are using EclipseLink with MySQL Database. EclipseLink is a popular open source ORM (Object Relation Mapping) tool for Java platform used for mapping an entity to a traditional relational database like Oracle, MySQL etc.

Developers can check the below table for the different databases which are available with EclipseLink examples:

DatabaseDriver classJar name
MySQLcom.mysql.jdbc.Drivermysql-connector-java-5.1.25-bin.jar (exact name depends on version)
Apache Derbyorg.apache.derby.jdbc.EmbeddedDriverderby.jar
PostgreSQLorg.postgresql.Driverpostgresql-8.4-701.jdbc4.jar (exact name depends on PostgreSQL version)
SQL Server (Microsoft driver)

1.1 JPA Benefits

There are many advantages of using the JPA framework, for e.g.

  • The benefit of using the JPA framework over any specific Object Relational Model (ORM) related libraries like Hibernate, iBatis etc. is that developers do not change the code when they change the vendor
  • The code is loosely coupled with the underlying ORM framework
  • Improves data security and data access to the users by using host and query languages
  • Improves application performance by reducing the data redundancy
  • Greater data integrity and independence of applications programs
  • Provides simple querying of data

1.2 How it can be achieved?

Programmers can achieve persistence in their application by introducing the persistence.xml in their code, which has to be located in the META-INF directory in the project classpath. One persistence.xml file can include definitions for one or more persistence units. This file plays a crucial role in the concept of JPA as in this configuration file, developers will register the database and specify the entity class. Let’s take a look and understand the sample code.

Sample persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
	xmlns="" xmlns:xsi=""
	<persistence-unit name="TestPersistence" transaction-type="RESOURCE_LOCAL">
		<class><!-- Entity Manager Class Name --></class>
			<property name="javax.persistence.jdbc.driver" value="Database Driver Name" />
			<property name="javax.persistence.jdbc.url" value="Database Url" />
			<property name="javax.persistence.jdbc.user" value="Database Username" />
			<property name="javax.persistence.jdbc.password" value="Database Password" />

The persistence.xml file indicates that there is only one Persistence Unit mapped with the name TestPersistence and the transaction type for this Persistence Unit is RESOURCE_LOCAL. There are two types of transactions:

  • JTA

If developers select the RESOURCE_LOCAL, then the transaction will be managed by the JPA Provider Implementation in use. If JTA is specified, then the transactions will be managed by the Application Server.
Do remember, if a developer only wants to have JPA transactions, then RESOURCE_LOCAL is a good choice. But, if a developer would like the transactions to contain resources other than JPA, like EJBs, JMS then JTA is the correct choice.

1.3 Download & Install EclipseLink

You can watch this video in order to download and install the JPA in Eclipse via the EclipseLink.

1.4 Download & Install MySQL

You can watch this video in order to download and install the MySQL database on your Windows Operating system.

Now, open up the Eclipse Ide and let’s see how to implement and define the JPA Persistence units in the persistence.xml.

2. Java persistence.xml Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MySQL and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 1: JPA Persistence Application’s Project Structure
Fig. 1: Application’s Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 3: Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters
Fig. 4: Archetype Parameters

Click on finish and the creation of a maven project will be completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:


<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">

We can start adding the dependencies that developers want like Eclipse Link, MySQL Connector Jar, and Hibernate etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Database & Table Creation

The following MySQL script is used to create a database called jpaDemoDb with table: farmer. Open the MySQL or the workbench terminal and execute the SQL script:


USE jpaDemoDb;

  name VARCHAR(120) NOT NULL,  
  village VARCHAR(200) NOT NULL,

DESC farmer;

If everything goes well, the database and the table will be shown in the MySQL Workbench.

Fig. 5: Database & Table Creation
Fig. 5: Database & Table Creation

3.2 Maven Dependencies

In this example, we are using the stable Hibernate, MySQL, and Eclipse Link version in order to support the JPA Content and make a successful database connection. The rest dependencies will be automatically resolved by Maven and the updated file will have the following code:


<project xmlns="" xmlns:xsi=""
		<!-- -->
		<!-- -->
		<!-- -->

3.3 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 6: Java Package Creation
Fig. 6: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.jpa.demo.

Fig. 7: Java Package Name (com.jcg.jpa.demo)
Fig. 7: Java Package Name (com.jcg.jpa.demo)

Once the package is created, we will need to create the model and the implementation classes. Right-click on the newly created package, New -> Class.

Fig. 8: Java Class Creation
Fig. 8: Java Class Creation

A new pop window will open and enter the file name as: Farmer. The model class will be created inside the package: com.jcg.jpa.demo.

Fig. 9: Java Class (
Fig. 9: Java Class (

Repeat the step (i.e. Fig. 8) and enter the filename as: JPADemo. The implementation class will be created inside the package: com.jcg.jpa.demo.

Fig 10: Java Class (
Fig 10: Java Class (

3.3.1 Implementation of Model Class

This class simply maps a row in the farmer table to a Java object. Add the following code to it:

package com.jcg.jpa.demo;

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

public class Farmer {

	private int id;

	private String name;

	private String village;

	public int getId() {
		return id;

	public void setId(int id) { = id;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public String getVillage() {
		return village;

	public void setVillage(String village) {
		this.village = village;

3.3.2 Implementation of Utility Class

This is the service class which implements the Java Persistence API to perform a database transaction (i.e. SQL INSERT Operation). Add the following code to it:

package com.jcg.jpa.demo;

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

public class JPADemo {

	private static final EntityManagerFactory emFactoryObj;
	private static final String PERSISTENCE_UNIT_NAME = "JPADemo";	

	static {
		emFactoryObj = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

	// This Method Is Used To Retrieve The 'EntityManager' Object
	public static EntityManager getEntityManager() {
		return emFactoryObj.createEntityManager();

	public static void main(String[] args) {

		EntityManager entityMgr = getEntityManager();

		Farmer farmObj = new Farmer();
		farmObj.setName("Harry Potter");
		farmObj.setVillage("Scottish Highlands");


		System.out.println("Record Successfully Inserted In The Database");

3.4 Database Configuration File

Developers can achieve persistence in their application by introducing the persistence.xml in their code. This module plays a crucial role in the concept of JPA as in this configuration file we will register the database and specify the entity class. Create a directory META-INF in the src/main/java folder and create the file persistence.xml inside it. Add the following code to it:


<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
	xmlns="" xmlns:xsi=""
	<persistence-unit name="JPADemo" transaction-type="RESOURCE_LOCAL">
			<!-- Configuring The Database Connection Details -->
			<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpaDemoDb" />
			<property name="javax.persistence.jdbc.user" value="root" />
			<property name="javax.persistence.jdbc.password" value="" />			


  • In this example, we are connecting the application with the MySQL database. So, developers must add the MySQL-connector-java-<version>-bin.jar to the project
  • We have kept the javax.persistence.jdbc.password value as blank for simplicity, however, it is pure unto the user to keep it blank or set it during the MySQL configuration. If the user sets it, we need to provide the same password to this string

4. Run the Application

To run the application, Right click on the JPADemo class, Run As -> Java Application. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 11: Run Application
Fig. 11: Run Application

5. Project Demo

Hereafter running the code, the application shows the following status as output:

Fig. 12: Application Output
Fig. 12: Application Output

That’s all for this post. Happy Learning!!

6. Conclusion

Through this example, we learned about the JPA implementation in Java. I hope this article served you whatever you were looking for. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of JPA persistence.xml.

You can download the full source code of this example here: JPADemo

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

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

I have read and agree to the terms & conditions



An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Notify of

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

Newest Most Voted
Inline Feedbacks
View all comments
4 years ago

from “Sample persistence xml” is not accurate. It is entity’s class name and not manager’s name.

3 years ago

Thank you very much!figured out :)

10 months ago

Thanks a lot! Help-me a lot!

Back to top button