Skip to main content

What is JPA?

·345 words·2 mins
Programming Databases
Alejandro Duarte
Author
Alejandro Duarte
Alejandro Duarte is a Software Engineer, published author, and award winner. He currently works for MariaDB plc as a Developer Relations Engineer. Starting his coding journey at 13 with BASIC on a rudimentary black screen, Alejandro quickly transitioned to C, C++, and Java during his academic years at the National University of Colombia. Relocating first to the UK and then to Finland, Alejandro deepened his involvement in the open-source community. He’s a recognized figure in Java circles, credited with articles and videos amassing millions of views, and presentations at international events.

JPA stands for Jakarta Persistence API (previously, Java Persistence API). It’s an API specification for database connectivity in Java applications. Since JPA is only a specification, you need an implementation in order to use it. The most popular implementation is Hibernate ORM.

ORM stands for Object/Relational Mapping and is a technique to transform SQL tables to Java (or any other programming language) objects and vice versa. For example, maybe you have a programming_language table in the database and want to read rows from there and store them in Java objects of a class you created, for example, ProgrammingLanguage. What you have to do is use JPA annotations (or equivalent XML configurations, which, to be honest, it’s been years since I saw a project using XML instead of JPA annotations) to tell the ORM framework how to put the data from the database in the Java fields and how to put data from the fields in the SQL table. Here’s an example:

import jakarta.persistence.*;

@Entity
@Table(name = "programming_language")
public class ProgrammingLanguage {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "pl_id")
    private Integer id;

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

    @Column(name = "pl_rating")
    private Integer rating;

    ... equals, hashCode, setters, getters ...
}

This allows you to read and write data. For example:

EntityManagerFactory entityManagerFactory =
    Persistence.createEntityManagerFactory("jpa-demo-local");

EntityManager entityManager = entityManagerFactory.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();

transaction.begin();

// write data:
entityManager.persist(new ProgrammingLanguage("Java", 10));

// read data:
List<ProgrammingLanguage> list = entityManager.createQuery(
		"select p from ProgrammingLanguage p where p.rating > 5",
		ProgrammingLanguage.class
).getResultList();

transaction.commit(); // or transaction.rollback();

In order for this to work you also need to define a Persistence Unit. This is an XML file called persistence.xml that defines the name used to create the EntityManagerFactory in the previous snippet of code plus the database connection details:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="jpa-demo-local" transaction-type="RESOURCE_LOCAL">
        <properties>
            <property name="jakarta.persistence.jdbc.url" value="jdbc:mariadb://localhost:3306/jpa_demo"/>
            <property name="jakarta.persistence.jdbc.user" value="user"/>
            <property name="jakarta.persistence.jdbc.password" value="password"/>
            <property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>
        </properties>
    </persistence-unit>
</persistence>

This really was an extremely short introduction, but I recorded a more detailed yet still introductory video that demonstrates how to use JPA with Hibernate. Check it out:

Enjoyed this post? I can help your team implement similar solutions—contact me to learn more.

Related

What is a database connection pool?
·239 words·2 mins
Programming Databases
A database connection pool stores ready-to-use database connections that threads can borrow when they need them, and return when they finish the work with the database.
How to execute SQL queries from Java (and prevent SQL injections)
·212 words·1 min
Programming Databases
To run SQL queries in Java, you need a Connection object.
How to open and close JDBC connections
·134 words·1 min
Programming Databases
To open and close database connections in Java, get a JDBC driver for your database.