JPA
JPA is the Jakarta persistence API: annotations and interfaces for mapping classes to tables. An EntityManager loads and saves entities. Hibernate is the usual implementation.
Detailed Explanation
You mark a class @Entity, give it an @Id, and map columns. The persistence context is a first-level cache: one entity instance per id for the life of the EntityManager (or the Spring transaction). find, persist, merge, and remove are the verbs. JPQL is an object query language; Criteria is the type-safe cousin; you can still run native SQL.
JPA is a specification. Hibernate, EclipseLink, and others implement it. Spring Data JPA generates repositories on top. You still need to know when a session is open: lazy associations throw LazyInitializationException if you touch them after the transaction ends.
You reach for JPA when the domain is entities with relations and most access is by id or simple queries. You reach for SQL when reporting, batch jobs, or odd queries fight the model. You do not use JPA as a way to avoid learning SQL; the generated SQL is your problem when it is slow.
The cost of a wide entity graph is N+1 queries and huge flushes. The cost of merge on a detached object is a select plus write you did not expect. The cost of equals/hashCode on mutable ids is broken sets. Use the id after persist, or a business key, consistently.
Transactions define the session in Spring. @Transactional on the service, not the controller, is the usual boundary. Flush happens before query or commit. You can flush by hand when you need the id of a generated row before the next statement.
Model the tables you have, not a fantasy graph. A @ManyToMany with a default join table is easy to write and hard to migrate. An explicit link entity is usually clearer. Prefer Long ids and a no-arg constructor for the provider. Keep entities out of controller return types so JSON does not walk the whole graph. JPA is a mapping layer. It is not a reason to stop writing SQL for the queries that matter.
Code Examples
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
protected User() {}
public User(String name) {
this.name = name;
}
public Long id() {
return id;
}
}import jakarta.persistence.EntityManager;
public class Users {
static User load(EntityManager em, Long id) {
return em.find(User.class, id);
}
}Common Gotchas
Lazy load after the session closes throws `LazyInitializationException`
fetch in the transaction or use a query with join fetch.
`equals` on a transient entity without an id is fragile
pick a strategy and keep it.
`merge` is not `persist`
it copies state onto a managed instance.