JPA

Basic Java
≈ 2 min read

Objects instead of manually assembling SQL results

With JDBC, an application works directly with SQL, query parameters, and result rows. JPA raises the abstraction level: ordinary Java objects can be mapped to database tables, while saving, finding, and changing those objects is delegated to a persistence provider such as Hibernate.

JPA is a specification of APIs and object-relational mapping rules, not a particular library or database. In modern code, its types live in the jakarta.persistence package.

What this section covers

  • JPA Basics. We will build the overall picture: the provider, EntityManager, and working with objects instead of manually processing result rows.
  • Entity. We will see what kind of class can represent a database record and how its identifier and fields are defined.
  • Entity Lifecycle. We will see why the same object can be new, managed, detached, or removed.
  • Relationships Between Entities. We will connect objects with one-to-one, one-to-many, many-to-one, and many-to-many relationships.
  • FetchType and Data Loading. We will examine when related data is loaded immediately and when it is loaded only when needed.
  • Cascade Operations. We will learn to control whether operations on one Entity propagate to related objects.
  • Persistence Context. We will understand why JPA tracks managed objects and how that relates to automatic data updates.
  • JPQL. We will learn to write queries in terms of Entity classes and their fields.
  • JPA Transactions. We will connect Entity changes with transaction boundaries.
  • N+1 Problem. We will see a common extra-query problem and learn to recognize it in code.

These topics form one model: first an object becomes an Entity, then JPA manages its state, relationships, and loading inside a persistence context. After that, queries and transactions no longer look like isolated API calls, but like parts of one data-access mechanism.

User user = entityManager.find(User.class, 42L);
System.out.println(user.getName());

After this section, a short fragment like this will reveal the whole chain: which Entity is being found, who manages its state, and when changes may reach the database.