JPA Tutorial for Beginners: A Comprehensive Guide

This article provides a comprehensive tutorial for beginners on the Java Persistence API (JPA). JPA simplifies database programming for Java developers, reducing development time and increasing productivity. This tutorial will guide you through the fundamentals of JPA, its implementation with Hibernate, and how to set up a Java Maven project in Eclipse to work with a MySQL database.

Prerequisites

Before you begin, ensure you have the following software installed on your computer:

  • Java Development Kit (JDK 1.8 or above)
  • MySQL, including MySQL database server, MySQL Command Line Client, and MySQL Workbench tool (MySQL 5.5 or above)
  • Eclipse IDE (Neon or later)

Tutorial Steps

This tutorial covers the following key steps:

  1. Overview of JPA and Hibernate
  2. Create MySQL Database
  3. Setup Java Maven Project in Eclipse
  4. Code Model Class
  5. Create JPA Configuration File (persistence.xml)
  6. Understand EntityManager and EntityManagerFactory
  7. Code a Test Program

1. Overview of JPA and Hibernate

Before diving into the code, let's understand the fundamentals of JPA and Hibernate.

Java Persistence API (JPA)

JPA is a Java API specification for managing relational data in applications using Java SE and Java EE. It defines a standard way to simplify database programming for developers, reduce development time, and increase productivity. When using JPA, you import interfaces and classes from the javax.persistence package.

Read also: Unlocking Potential with Early Learning

JPA defines Java Persistence Query Language (JPQL), an object-oriented query language. The syntax of JPQL is similar to SQL but operates against Java objects rather than directly with database tables.

JPA is a specification, and Hibernate is one of its implementations, along with others like EclipseLink and OpenJPA.

Hibernate Framework

Hibernate is a popular Object Relational Mapping (ORM) framework that simplifies database programming for developers. Developed before JPA, Hibernate restructured itself to become a JPA implementation after JPA became a standard.

The Hibernate framework consists of several components: Hibernate ORM, Hibernate Search, Hibernate Validator, Hibernate CGM, and Hibernate Tools. In this tutorial, we use Hibernate ORM, the core component, for mapping Java model classes to tables in a relational database. Object-Relational Mapping (ORM) is the process of converting Java objects to database tables, allowing interaction with a relational database without writing SQL.

2. Create MySQL Database

First, let’s create a database named UsersDB.

Read also: Explore AALAS Learning Library

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Using the desc users command in MySQL Command Line Client, the structure of the table looks like this:

Note that the column user_id is the table’s primary key and is auto-increment.

3. Setup Java Maven Project in Eclipse

  1. Create a Maven Project:In Eclipse IDE, click File > New > Project… and select Maven > Maven Project in the New Project dialog. Then click Next.

  2. Configure Project:In the next screen, check the option ‘Create a simple project (skip archetype selection)’, and then click Next.

    Read also: Understanding PLCs

  3. Enter Project Information:In the New Maven Project screen, enter the project’s information as follows:

    • Group Id: net.codejava.hibernate
    • Artifact Id: HibernateJPABeginner

    Leave other settings as they are and click Finish.

  4. Project Structure:In the Project Explorer view, you will see the project created with the following structure:

  5. Configure Maven Dependencies:Next, add dependencies in Maven’s Project Object Model (pom.xml) for Hibernate, JPA, and MySQL Connector Java.

  6. Add Dependencies:Open the pom.xml file and add the following dependencies inside the <dependencies> tag:

 org.hibernate hibernate-core 5.6.3.Final mysql mysql-connector-java 8.0.27

Maven automatically downloads the required JAR files, which are shown under the Maven Dependencies node in the project. Specifying the dependency hibernate-core allows Maven to analyze and download all dependencies of hibernate-core as well.

  1. Create a Java Package:Create a new Java package named net.codejava.hibernate under the src/main/java folder. This package will contain the Java classes.

4. Code Model Class

Next, create a domain model class named User. This is a POJO (Plain Old Java Object) class with instance fields and getter and setter methods. By default, the ORM framework understands that the class name is the same as the table name. By default, Hibernate can implicitly infer the mapping based on the field name and field type of the class. But if the field name and the corresponding column name are different, this annotation must be used explicitly.

package net.codejava.hibernate;import javax.persistence.*;@Entity@Table(name = "users")public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_id") private int id; @Column(name = "email") private String email; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "password") private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } 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 getPassword() { return password; } public void setPassword(String password) { this.password = password; }}

5. Create JPA Configuration File (persistence.xml)

Create an XML configuration file for JPA called persistence.xml to tell Hibernate how to connect to the database. This file must be in the classpath, under the META-INF folder.

  1. Create META-INF Folder:Under the src/main/resources folder, create a new folder named META-INF (Right-click, select New > Other… > Folder).
  2. Create persistence.xml File:Right-click on the newly created folder META-INF, select New > Other… > XML > XML File. Enter the file name as persistence.xml.
  3. Add Configuration:Add the following XML configuration to the persistence.xml file:
 UsersDB com.mysql.cj.jdbc.Driver jdbc:mysql://localhost:3306/UsersDB root admin true true

The root element <persistence> specifies the version of JPA to be used (JPA version 2.1). The element <persistence-unit> specifies a unit of persistence with a name (UsersDB), which will be looked up by Java code.

The following properties are specified for database connection information:

  • javax.persistence.jdbc.url: Specifies the JDBC URL pointing to the database.
  • javax.persistence.jdbc.user: Specifies the username of the account with privileges to access the database.
  • javax.persistence.jdbc.password: Specifies the user's password.
  • javax.persistence.jdbc.driver: Specifies the class name of the JDBC driver to be used. Here, MySQL Connector Java is used, so the name is com.mysql.cj.jdbc.Driver.
  • hibernate.show_sql: Tells Hibernate to show SQL statements in the standard output.
  • hibernate.format_sql: Tells Hibernate to format the SQL statements.

Modify the values for url, user, and password accordingly.

6. Understand EntityManager and EntityManagerFactory

Before we write a test program, let's understand a couple of key interfaces in JPA.

EntityManager

An EntityManager instance is associated with a persistence context and is used to interact with the database. A persistence context is a set of entity instances, which are objects or instances of the model classes. The EntityManager is used to manage entity instances and their life cycle, such as creating, updating, removing, finding, and querying entities. The EntityManager is the primary JPA interface for interacting with the persistence context and acts as a bridge between the Java application and the database.

EntityManagerFactory

An EntityManagerFactory is used to create an EntityManager. It is associated with a persistence unit. In Java SE environments, an EntityManagerFactory can be obtained from the Persistence class.

Here are the typical steps to manage entity instances via JPA:

  1. Create an EntityManagerFactory from a persistence unit.
  2. Create an EntityManager from the EntityManagerFactory.
  3. Begin a transaction.
  4. Manage entity instances (create, update, remove, find, query, etc.).
  5. Commit the transaction.
  6. Close the EntityManager and EntityManagerFactory.

7. Code a Test Program

Now, let’s write some code to create, update, find, query, and remove User entity instances using JPA.

package net.codejava.hibernate;import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;public class TestProgram { public static void main(String[] args) { EntityManagerFactory entityManagerFactory = null; EntityManager entityManager = null; try { // Create an EntityManagerFactory from the persistence unit entityManagerFactory = Persistence.createEntityManagerFactory("UsersDB"); // Create an EntityManager from the EntityManagerFactory entityManager = entityManagerFactory.createEntityManager(); // Begin a transaction entityManager.getTransaction().begin(); // Create a new User object User newUser = new User(); newUser.setEmail("[email protected]"); newUser.setFirstName("John"); newUser.setLastName("Doe"); newUser.setPassword("secret"); // Persist the new user to the database entityManager.persist(newUser); // Commit the transaction entityManager.getTransaction().commit(); System.out.println("New user created with ID: " + newUser.getId()); // Find an existing user User existingUser = entityManager.find(User.class, 1); if (existingUser != null) { System.out.println("Existing user: " + existingUser.getFirstName() + " " + existingUser.getLastName()); // Update the existing user entityManager.getTransaction().begin(); existingUser.setEmail("[email protected]"); entityManager.merge(existingUser); entityManager.getTransaction().commit(); System.out.println("User updated successfully."); } else { System.out.println("User with ID 1 not found."); } // Remove a user entityManager.getTransaction().begin(); User reference = entityManager.getReference(User.class, 1); if (reference != null) { entityManager.remove(reference); System.out.println("User with ID 1 removed."); } else { System.out.println("User with ID 1 not found for removal."); } entityManager.getTransaction().commit(); } catch (Exception e) { if (entityManager != null && entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } e.printStackTrace(); } finally { // Close the EntityManager and EntityManagerFactory if (entityManager != null) { entityManager.close(); } if (entityManagerFactory != null) { entityManagerFactory.close(); } } }}

Run this program. Hibernate prints the SQL statement, which is nicely formatted. This means the program has been executed successfully. Check the result by typing the command select * from users in MySQL Command Line Client tool. A new row has been created without writing any SQL statement.

Updating an Entity Instance

To update an entity, you need to specify the ID of the object and use the merge(Object) method of the EntityManager class.

entityManager.merge(existingUser);

Finding an Entity Instance

To find an entity from the database, use the method find(Class<T> entityClass, Object primaryKey) of the EntityManager class.

User user = entityManager.find(User.class, 1);System.out.println(user.getPassword());

Removing an Entity Instance

To remove an entity, use the remove(Object) method of the EntityManager class.

entityManager.remove(reference);

This code removes the User object with ID = 1 from the database by looking up a reference based on the class type (User.class) and primary key value (1), then removing the reference.

tags: #JPA #tutorial #for #beginners

Popular posts: