FOR DEVELOPERS

Java Persistence API (JPA) For Database Access

JPA for Database Access

Java Persistence API (JPA) is a framework that provides a set of specifications and interfaces for managing relational data in Java applications. It is part of the Java EE (Enterprise Edition) platform and allows developers to map Java objects to relational database tables using an object-relational mapping (ORM) approach. JPA provides a convenient way to interact with databases without having to write low-level SQL code.

In this article, we will be exploring the concepts of Java Persistence API (JPA) for database access. We will explore ORM, discuss Java persistence with Hibernate, and learn how to configure Hibernate with different methods.

What is ORM?

ORM stands for Object-Relational Mapping, which is a programming technique that allows software engineers to write in any programming language of their choice and encapsulate (hide) the code needed to manipulate the data, so you don't use SQL anymore; you interact directly with an object in the same language you're writing. The goal of ORM is to help software engineers work with databases by allowing them to interact with the database using object-oriented programming concepts, such as classes, objects, and methods, rather than having to write low-level SQL code.

For example, working with data is best explained when you have a Java application, you have a database, and you use JDBC to connect the Java application to the database. Where we have a class and the class structure, that class has some variables, and then we have a table. Next we will implement, our table name will be the class name, and the columns will be the class variable. And, this is how we use object-relational mapping.

To implement ORM in Java, we need some tools. These tools include Hibernate, Entity Framework, Sequelize, SQLAlchemy, and Dapper. These are the most popular tools. You can make use of any of these tools and make them work. You can build an ORM application using Hibernate.

However, we have a problem with ORM. In Java, we work with objects, and a database has rows and columns. How do we save the object in a database with rows and columns in a way that we don’t have to fetch values one after the other?

To save objects in a database with rows and columns, we have to use a mechanism that maps the objects to the relational database model. This is where the Java Persistence API (JPA) comes in.

What is JPA?

JPA stands for Java Persistence API. It is an object-relational mapping (ORM) framework that allows us to map Java objects to tables in a relational database. In other words, JPA provides a way to persist Java objects in a database using a set of annotations that define the mapping between Java classes and database tables.

JPA in Java is typically used in enterprise applications that require access to relational databases, such as web applications and enterprise resource planning (ERP) systems. JPA provides a standardized approach to working with databases that is portable across different ORM frameworks.

How to implement JPA in Java

To implement JPA, you first need to include the JPA library in your project. You can do this by adding the following dependency to your project:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
<version>2.2</version>
</dependency>

You also need to choose an implementation of the JPA specification, such as Hibernate, and add its dependencies to your project. In this tutorial we will be using Hibernate.

When we define a Java class that needs to be persistent in a database, we annotate it with the JPA annotations. These annotations specify the mapping between the Java class and the database table. Let's see how it works.

Java Persistence with Hibernate

Java Persistence API (JPA) is a specification for Object-Relational Mapping (ORM) in Java. Hibernate is an implementation of the JPA specification and provides a set of APIs for interacting with databases using objects. To implement Hibernate with JPA, you need to include the Hibernate dependencies in your project. You can do this by adding the following dependencies to your project:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.6.0.Final</version></dependency><dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
<version>5.6.0.Final</version>
</dependency>

How to configure Hibernate

You also need to configure Hibernate using a persistence.xml file, which should be placed in the META-INF folder of your project. Here is an example of a persistence.xml file:

<persistence 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_2.xsd"
             version="2.2">
<persistence-unit name="my-persistence-unit"
transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>com.example.Customer</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mydatabase"/>
            <property name="javax.persistence.jdbc.user" value="myuser"/>
            <property name="javax.persistence.jdbc.password" value="mypassword"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>
</persistence-unit>
</persistence>

This file configures a persistence unit named "my-persistence-unit" with transaction-type "RESOURCE_LOCAL". It specifies the provider as "org.hibernate.jpa.HibernatePersistenceProvider" and lists the entity classes that should be managed by this persistence unit. It also includes properties such as the JDBC driver, URL, username, password, dialect, and SQL logging settings.

How to create entity management class

To create an EntityManagerFactory instance, see the example below

EntityManagerFactory entityManagerFactory = 
Persistence.createEntityManagerFactory("my-persistence-unit");

From the code above, we create an EntityManagerFactory instance based on the configuration in the persistence.xml file.

How to create entity management instance

To create an EntityManager instance, see the example below:

EntityManager entityManager = entityManagerFactory.createEntityManager();

This code creates an EntityManager instance, which you can use to perform database operations such as fetching and saving entities.

How to fetch an entity from database

To fetch an entity from the database, you can use the "find" method of the EntityManager class, as shown below:

Customer customer = entityManager.find(Customer.class, 1L);

The code above fetches the customer with ID 1 from the database and maps it to a "Customer" object.

How to save an entity to the database

To save an entity to the database, you can use the "persist" method of the EntityManager class, as shown below:

entityManager.getTransaction().begin();
Customer customer = new Customer();
customer.setFirstName("Isah");
customer.setLastName("Jacob");

entityManager.persist(customer);

entityManager.getTransaction().commit();

The code above creates a new "Customer" object, sets its first name and last name, and then persists it to the database. The transaction is committed at the end, which ensures that the changes are saved to the database.

In JPA, you can use annotations such as "@Entity" and "@Id" to map Java objects to database tables.

Below is an example of a "Customer" entity class:

@Entity @Table(name = "customers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = &quot;first_name&quot;)
private String firstName;

@Column(name = &quot;last_name&quot;)
private String lastName;

// you can add getters and setters here

}

The code above defines a "Customer" entity class with three fields: "id" "firstName" and "lastName." The "@Entity" annotation specifies that this class should be mapped to a database table.

The "@Id" annotation specifies that the "id" field is the primary key for this table, and the "@GeneratedValue" annotation specifies that this field should be automatically generated by the database.

How to retrieve a "Customer" object by its ID

Customer customer = entityManager.find(Customer.class, 1L);

This code retrieves the "Customer" object with ID 1 from the database.

In this example, we have been able to use JPA, which provides a set of APIs for mapping Java objects to database tables and performing database operations using these objects. We also discuss Hibernate as an implementation of JPA that provides additional features and capabilities. You should be able to use Hibernate with JPA, include the Hibernate dependencies in your project, configure Hibernate using a persistence.xml file, and use the EntityManager to perform database operations.

NOTE: If you are building your application purely on Hibernate, you will face issue of shifting, but if you build your application based on JPA, it will be easier for you to switch between tools. JPA is just a specification, so if you want to work with JPA, you don’t need Hibernate for the implementation. If you are building a Hibernate project, you are working with Hibernate. If you are building a JPA project, then either you are using Hibernate for the implementation or Sequelize; you cannot simply make a JPA application without any of these tools.

Conclusion

We’ve learned about Java Persistence API (JPA) for database access, ORM, JPA and their implementations. We also learned how to configure Hibernate and how to create entity management classes and the different methods to use. Try the various methods discussed above and see the benefit of JPA in database access.

Author

  • Java Persistence API (JPA) For Database Access

    Isah Jacob

    Jacob has more than two years of experience as a technical writer and software engineer. He is a skilled technical writer who can clearly explain complex concepts to a broad audience.

Frequently Asked Questions

Data Persistence is a means for an application to persist and retrieve information from a non-volatile storage system. The Java Persistence API (JPA) provides a mechanism for managing, persistence, and object-relational mapping and functions since the EJB 3.0 specifications.

ORM stands for Object-Relational Mapping (ORM) it is a programming technique for converting data between relational databases and object oriented programming languages such as Java, C#, etc.

Enable Hibernate support for an existing project. Open the build file in the editor (pom. xml or build. gradle depending on the build tool that you use in your project). Press Ctrl+Shift+O to import the changes.

View more FAQs
Press

Press

What’s up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work. Checkout our blog here.
Contact

Contact

Have any questions? We’d love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.