JPA - Installation

Last Updated : 23 Jul, 2025

The Java Persistence API (JPA) is the specification for the accessing, persisting and managing the data between java objects and the relational database. It can provides the framework for the mapping Java objects to the database tables and it can allowing the developers to work with the data in the more object-oriented way of the application.

Java Persistence API ( JPI )

The Java Persistence API is the specification for the managing the relational data in the Java applications. JPA can provides the object-relational mapping (ORM) framework that allows the developers to map the Java objects to database tables and perform the CRUD operations in the more intuitive and object-oriented manner.

Key Terminologies in JPA

  1. Entity: It is the lightweight, persistent the domain object. Typically, the entity can represents the table in the relational database and each entity instance corresponds to the row in that table.
  2. EntityManager: It is an interface provides the method for interacting with the persistence context. It is responisible for the managing the lifecycle of the entity instances such as persisting, finding and removing the entities of the application.
  3. Persistence Unit: The persistence unit defines the set of all the entity classes that are managed by the EntityManager instances in the application. It can defined in the persistence.xml configuration files of the project.
  4. Persistence Context: It is set of managed entity instances within which the EntityManager operates. The persistence context acts as the first level cache where all the entities are managed.
  5. Transactions: It can be used to group the multiple operations into the single unit of work. It can ensuring the data integrity and consistency. JPA can supports both the resource-local and JTA (Java Transaction API) transactions.

Setting up the JPA in a Jakarta EE Project

Step 1: Create the Jakarta Project

We need to create the Jakarta EE project using the IntelliJ Ultimate and add the name and select template as library of the application. Click on next.

jpai1-compressed

Step 2: Dependencies

We can dd the dependencies of the Persistence(JPA) of the application.

jpai2-compressed

MySQL Dependency:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>

Step 3: File Structure

Once the create the JPA project then the file structure looks like the below image.

jpai3

Step 4: Create the Employee Entity

Java
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String lastName;
    private String email;

    // Getters and setters


    public Long getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Step 5: Create the MainApplication

Java
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.EntityTransaction;
import jakarta.persistence.Persistence;

public class MainApplication {

    public static void main(String[] args) {
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myPersistenceUnit");
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();


        // Create a new Employee entity
        Employee employee = new Employee();
        employee.setFirstName("John");
        employee.setLastName("Doe");
        employee.setEmail("john.doe@example.com");


        transaction.begin();

        // Persist the employee entity
        entityManager.persist(employee);

        transaction.commit();
        System.out.println("Persisted Employee:");
        System.out.println("ID: " + employee.getId());
        System.out.println("First Name: " + employee.getFirstName());
        System.out.println("Last Name: " + employee.getLastName());
        System.out.println("Email: " + employee.getEmail());



        entityManager.close();
        entityManagerFactory.close();
    }
}

Step 6: Configuring persistence.xml

We can create the persistence.xml file in the src/main/resource directory. This file contains the configuration for the MySQL database and JPA persistence unit of the application.

XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence/"
             xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence/ https://jakarta.ee/xml/ns/persistence//persistence_3_0.xsd"
             version="3.0">
  <persistence-unit name="myPersistenceUnit">
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/example"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="javax.persistence.jdbc.password" value=""/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
  </persistence-unit>
</persistence>

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0"
         xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>JPA-Demo1</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>JPA-Demo1</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>11</maven.compiler.target>
    <maven.compiler.source>11</maven.compiler.source>
    <junit.version>5.9.2</junit.version>
  </properties>

  <dependencies>
<dependency>
      <groupId>org.hibernate.orm</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>6.0.2.Final</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish.jaxb</groupId>
      <artifactId>jaxb-runtime</artifactId>
      <version>3.0.2</version>
    </dependency><dependency>
      <groupId>org.hibernate.validator</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>7.0.5.Final</version>
    </dependency>
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>8.0.28</version>
      </dependency>

      <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
      <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
      </dependency>  </dependencies>

  <build>
    <plugins>
    </plugins>
  </build>
</project>

Step 7: Run the application

Run the MainApplication class to see the output of the project. We can see the details of the persisted employee printed to the console.

Output Screenshot

jpailog-compressed

Further Topics

  • Entity Relationships: Explore how to define the relationships between the entities using JPA annotations such as @OneToOne, @OneToMany and @ManyToMany of the application.
  • JPQL: It can defined as Java Persistence Query Language. Learn how to use the JPQL to query the database using the entity objects.
  • Criteria API: Understand how to use the criteria API to the create type-safe queries in the JPA application.
  • Transaction Management: Dive deeper into the managing transactions in the JPA to ensure the data integrity and consistency of the application.

This setup can provides the comprehensive overview of the setting up and using the JPA in the Java application. By the following these steps, we can perform the CRUD operations on the application.

Comment
Article Tags:

Explore