Java Persistence API (JPA) Lecture Notes

Java Persistence API (JPA)

Overview

  • JPA is a specification that provides a way to manage relational data in Java applications.

  • The main purpose is to store business entities as relational entities.

Key Components of JPA

  • EntityManagerFactory: A factory class that creates and manages multiple instances of EntityManager.

  • EntityManager: An interface that manages persistence operations on objects.

  • Entity: Represents a persistence object that stores as records in a database.

  • Entity Transaction: Manages transaction operations related to persistence.

  • Persistence: Provides methods to obtain EntityManagerFactory instance.

  • Query: Works as a factory for query instances.

JPA Queries

There are three basic types of JPA Queries:

  1. JPQL (Java Persistence Query Language): A query language similar to SQL but works with Java objects instead of database tables.

  2. TypedQuery: A type-safe version of JPQL, preferred when the result type is known beforehand, enhancing reliability and testability.

  3. NamedQuery: A predefined, unchangeable query string that passes parameters instead of embedding literals into the query string.

  4. NativeQuery: Written in plain SQL syntax.

  5. Criteria API Query: Constructed programmatically through various methods.

Java Persistence Query Language (JPQL)

  • Definition: JPQL is defined in the JPA specification for creating queries against entities stored in a relational database. It is developed based on SQL syntax but operates on Java classes and instances rather than directly on database records.

  • Capabilities:

    • Retrieve information using the SELECT clause.

    • Perform bulk updates with the UPDATE clause.

    • Execute deletions using the DELETE clause.

JPQL Examples

  • Scalar Function Example:

  import java.util.List;
  import javax.persistence.EntityManager;
  import javax.persistence.EntityManagerFactory;
  import javax.persistence.Persistence;
  import javax.persistence.Query;

  public class ScalarAndAggregateFunctions {
      public static void main(String[] args) {
          EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("Eclips");
          EntityManager entitymanager = emfactory.createEntityManager();

          // Scalar function example
          Query query = entitymanager.createQuery("SELECT UPPER(e.ename) FROM Employee e");
          List<String> list = query.getResultList();
          for(String e : list) {
              System.out.println("Employee NAME: " + e);
          }

          // Aggregate function example
          Query query1 = entitymanager.createQuery("SELECT MAX(e.salary) FROM Employee e");
          Double result = (Double) query1.getSingleResult();
          System.out.println("Max Employee Salary: " + result);

          entitymanager.close();
          emfactory.close();
      }
  }

JPA Examples

  • Adding an Employee: An example of adding an employee entity and demonstrating how to utilize the EntityManager for persistence operations can be derived from the code snippets.

  • Updating an Employee Entity:

  import javax.persistence.EntityManager;
  import javax.persistence.EntityManagerFactory;
  import javax.persistence.Persistence;
  import com.tutorialspoint.eclipselink.entity.Employee;

  public class UpdateEmployee {
      public static void main(String[] args) {
          EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("Eclips");
          EntityManager entitymanager = emfactory.createEntityManager();

          entitymanager.getTransaction().begin();
          Employee employee = entitymanager.find(Employee.class, 1201);
          // before update
          System.out.println(employee);
          employee.setSalary(46000);
          entitymanager.getTransaction().commit();
          // after update
          System.out.println(employee);
          entitymanager.close();
          emfactory.close();
      }
  }
  • Deleting an Employee Entity: While similar to the update process, the key steps involve beginning a transaction, finding the employee by ID, and removing the entity.

Definitions and Concepts

  • EntityManager: Manages the operations for accessing and modifying persistent data. Each instance is associated with a specific persistence context.

  • Entity: Represents a domain object in your application that is persisted in the database.

  • Entity Transaction: Responsible for executing operations in a context-aware manner, managing the transactional environments in JPA applications.

Ethical and Practical Implications

  • The choice of JPQL versus native SQL can impact performance and portability.

  • Using named queries helps to avoid SQL injection attacks by parameterizing inputs, promoting security in accessing the database.