jpa

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)
http://www.mysql.com/downloads/connector/j/
HSQLDBorg.hsqldb.jdbcDriverhsqldb.jar
http://hsqldb.sourceforge.net
Sybasecom.sybase.jdbc3.jdbc.SybDriverjconnect.jar
http://www.sybase.com/products/allproductsa-z/softwaredeveloperkit/jconnect
Apache Derbyorg.apache.derby.jdbc.EmbeddedDriverderby.jar
http://db.apache.org/derby/
IBM DB2com.ibm.db2.jcc.DB2Driverdb2jcc4.jar
http://www-01.ibm.com/software/data/db2/linux-unix-windows/download.html
PostgreSQLorg.postgresql.Driverpostgresql-8.4-701.jdbc4.jar (exact name depends on PostgreSQL version)
http://jdbc.postgresql.org
SQL Server (Microsoft driver)com.microsoft.sqlserver.jdbc.SQLServerDriversqljdbc4.jar
http://msdn.microsoft.com/en-gb/data/aa937724%28en-us%29.aspx

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="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
	<persistence-unit name="TestPersistence" transaction-type="RESOURCE_LOCAL">
		<class><!-- Entity Manager Class Name --></class>
		<properties>
			<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" />
		</properties>
	</persistence-unit>
</persistence>

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
  • RESOURCE_LOCAL

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:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JPADemo</groupId>
	<artifactId>JPADemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
</project>

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:

CREATE DATABASE jpaDemoDb;

USE jpaDemoDb;

CREATE TABLE farmer (
  id INTEGER NOT NULL,
  name VARCHAR(120) NOT NULL,  
  village VARCHAR(200) NOT NULL,
  PRIMARY KEY(id)
);

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:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JPADemo</groupId>
	<artifactId>JPADemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.eclipse.persistence/eclipselink -->
		<dependency>
			<groupId>org.eclipse.persistence</groupId>
			<artifactId>eclipselink</artifactId>
			<version>2.5.2</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse.persistence</groupId>
			<artifactId>javax.persistence</artifactId>
			<version>2.0.0</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.40</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.2.8.Final</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.11.Final</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

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 (Farmer.java)
Fig. 9: Java Class (Farmer.java)

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 (JPADemo.java)
Fig 10: Java Class (JPADemo.java)

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:

Farmer.java

package com.jcg.jpa.demo;

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

@Entity
@Table(name="farmer")
public class Farmer {

	@Id
	@Column(name="id")
	private int id;

	@Column(name="name")
	private String name;

	@Column(name="village")
	private String village;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.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:

JPADemo.java

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();
		entityMgr.getTransaction().begin();

		Farmer farmObj = new Farmer();
		farmObj.setId(101);
		farmObj.setName("Harry Potter");
		farmObj.setVillage("Scottish Highlands");
		entityMgr.persist(farmObj);

		entityMgr.getTransaction().commit();

		entityMgr.clear();
		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:

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
	xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
	<persistence-unit name="JPADemo" transaction-type="RESOURCE_LOCAL">
		<class>com.jcg.jpa.demo.Farmer</class>		
		<properties>
			<!-- 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="" />			
		</properties>
	</persistence-unit>
</persistence>

Notes:

  • 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.

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

Yatin

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).
Subscribe
Notify of
guest

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

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Pawel
Pawel
5 years ago

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

Kolya
5 years ago

Thank you very much!figured out :)

Thiago
Thiago
2 years ago

Thanks a lot! Help-me a lot!

Back to top button