Java EE / Jakarta EE

Jakarta Persistence (JPA 3.1): Entities, Mapping and the Persistence Context

Intermediate9 min readUpdated

Jakarta Persistence is the object-relational mapping standard implemented by Hibernate and EclipseLink, and the persistence layer under Spring Data JPA. This guide explains the persistence unit and the EntityManager, the states an entity moves through, how to map identifiers, columns, embedded values and relationships, what lazy loading and cascades really do, and how optimistic locking protects updates — with the traps that produce N+1 queries, LazyInitializationException and lost updates.

What you will learn

  • Configure a persistence unit and obtain a container-managed EntityManager
  • Describe the entity life cycle and what persist, merge, remove, detach and flush do
  • Map identifiers, basic attributes, embeddables, enums and java.time types
  • Map one-to-many, many-to-one, one-to-one and many-to-many associations with the correct owning side
  • Choose fetch strategies, cascades, inheritance mappings and optimistic locking deliberately

Relational databases store rows; Java programs work with object graphs. Every application that uses both needs a mapping between them, and writing that mapping by hand — SQL for each operation, result-set-to-object code, identity bookkeeping — is repetitive and error-prone. Jakarta Persistence (JPA) standardises the mapping and the runtime that applies it, so you declare once how Order relates to the orders table and then work with objects. The runtime is not magic, though: an EntityManager tracks the objects it loaded, decides when to write them back and issues SQL that you did not write. Most JPA problems come from not knowing what it is doing on your behalf; this guide makes that visible.

Persistence units and the EntityManager

A persistence unit is a named set of entity classes plus the configuration to reach one database, declared in META-INF/persistence.xml. In a container, the data source is a JNDI reference and transactions are JTA's:

<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence
                                 https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"
             version="3.0">
  <persistence-unit name="shop" transaction-type="JTA">
    <jta-data-source>java:/jdbc/ShopDS</jta-data-source>
    <!-- entity classes are discovered by scanning the archive; list them only outside a container -->
    <properties>
      <property name="jakarta.persistence.schema-generation.database.action" value="none"/>
      <property name="hibernate.show_sql" value="false"/>   <!-- provider-specific; harmless if the provider is EclipseLink -->
    </properties>
  </persistence-unit>
</persistence>

transaction-type="RESOURCE_LOCAL" with jakarta.persistence.jdbc.url, user and password properties is the stand-alone form used in tests and Java SE programs; there you create an EntityManagerFactory with Persistence.createEntityManagerFactory("shop") and manage EntityTransaction yourself. Inside a Jakarta EE server you inject the manager and the container does the rest:

@PersistenceContext(unitName = "shop")
EntityManager em;          // container-managed, transaction-scoped: one persistence context per JTA transaction

The EntityManager is a facade over a persistence context: a map from identity (entity class plus primary key) to the single managed instance of that row. Within one context em.find(Order.class, 1L) called twice returns the same object, and no row is represented twice. A transaction-scoped context lives exactly as long as the JTA transaction and is flushed — pending changes turned into SQL — just before commit. Application-managed and extended contexts exist for special cases (stateful beans, batch jobs) but the transaction-scoped one is the default and the one to understand first.

The entity life cycle

An entity instance is always in one of four states, and the EntityManager methods move it between them:

StateMeaningHow you get there
New (transient)A plain object; the context knows nothing about itnew Order()
ManagedTracked by the context; changes are detected and written at flushpersist, find, getReference, a query result, merge's return value
DetachedWas managed by a context that is now closed, or was explicitly detachedTransaction ended, detach, clear, serialisation
RemovedScheduled for DELETE at flushremove on a managed instance

The most important consequence is automatic dirty checking: you do not call update. Load an entity, change a field inside the transaction, and the UPDATE happens at flush — including for entities you loaded through a query and modified incidentally. merge is the bridge from detached back to managed, and the detail everyone gets wrong once: it returns the managed copy and leaves the argument detached.

@Transactional
public Order rename(Long id, String newRef) {
    Order order = em.find(Order.class, id);   // managed
    order.setReference(newRef);               // dirty; UPDATE issued at flush, no explicit call
    return order;                              // becomes detached when the transaction commits
}

@Transactional
public Order update(Order detachedFromForm) {
    Order managed = em.merge(detachedFromForm);   // copies state onto the managed instance
    managed.setUpdatedAt(Instant.now());          // affects the row; detachedFromForm is untouched
    return managed;
}

getReference returns a proxy without hitting the database — ideal when you only need to set a foreign key. refresh reloads from the database, discarding changes. flush forces SQL out early (a query with FlushModeType.AUTO, the default, flushes anyway when it might read pending changes), and clear detaches everything, which is how batch jobs keep memory bounded.

Mapping a class to a table

An entity is a non-final class with a no-argument constructor (at least protected), annotated @Entity, with an identifier. Fields are mapped by default — every non-transient field becomes a column named after the field — so annotations are only needed where the default is wrong.

import java.math.BigDecimal;
import java.time.Instant;
import java.util.*;
import jakarta.persistence.*;

@Entity
@Table(name = "orders",                                 // "order" is a reserved word in SQL
       indexes = @Index(name = "ix_orders_customer", columnList = "customer_id"))
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "orders_seq")
    @SequenceGenerator(name = "orders_seq", sequenceName = "orders_seq", allocationSize = 50)
    private Long id;

    @Column(nullable = false, length = 20, unique = true)
    private String reference;

    @Enumerated(EnumType.STRING)                        // never ORDINAL: reordering the enum corrupts data
    @Column(nullable = false, length = 16)
    private OrderStatus status = OrderStatus.NEW;

    @Column(nullable = false)
    private Instant placedAt = Instant.now();           // java.time maps natively since JPA 2.2

    @Embedded
    private Address shippingAddress;                    // columns inlined into the orders table

    @Convert(converter = MoneyConverter.class)          // custom type <-> column, via AttributeConverter
    private Money total;

    @Version
    private long version;                               // optimistic locking, see below

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "customer_id")
    private Customer customer;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    @OrderBy("lineNo")
    private List<OrderLine> lines = new ArrayList<>();

    protected Order() { }                               // required by the specification

    public Order(Customer customer) { this.customer = customer; }

    public void addLine(Product product, int quantity) {
        var line = new OrderLine(this, product, quantity, lines.size() + 1);
        lines.add(line);                                // keep both sides consistent
    }
    // getters; setters only where the domain allows change
}

Identifiers

Choose the generation strategy with the database in mind:

  • SEQUENCE — the best default for PostgreSQL, Oracle and any database with sequences. With allocationSize the provider fetches a block of ids at once, so inserts do not need a round trip each. Keep the allocation size identical to the sequence's INCREMENT BY, or you get gaps and, on some providers, collisions.
  • IDENTITY — auto-increment columns (MySQL, SQL Server). Simple, but the id is only known after the INSERT, which forces the provider to insert immediately on persist and disables insert batching.
  • UUID — new in Persistence 3.1: the provider generates a java.util.UUID. Ids are globally unique and can be assigned client-side, at the cost of 16-byte keys and poorer index locality on some databases.
  • TABLE — portable but slow; avoid.
  • AUTO — lets the provider choose; explicit is better because the choice affects batching and schema.

Composite keys are supported with @EmbeddedId or @IdClass; they appear in legacy schemas and are worth avoiding in new ones.

Basic attributes, embeddables and converters

@Column controls name, nullability, length and precision; @Basic(fetch = LAZY) on a large @Lob asks the provider to defer loading it, although not all providers honour it without bytecode enhancement. @Transient excludes a field. @Embeddable classes group columns that belong together — an address, a money amount — without a table of their own, and @AttributeOverride renames their columns when the same embeddable appears twice. An AttributeConverter<X, Y> maps any Java type to a JDBC-supported column type and is the standard way to store value objects, encrypted strings or JSON blobs. @Temporal is only needed for legacy java.util.Date fields; use LocalDate, LocalDateTime, Instant or OffsetDateTime.

Relationships and the owning side

Associations are where mappings go wrong. The rule that resolves most confusion: the database has one foreign key, so one side of the association owns it, and only changes on the owning side are written.

  • @ManyToOne is always the owning side; the foreign key lives in its table. @JoinColumn names it.
  • @OneToMany(mappedBy = "order") is the inverse side. Adding a line to order.getLines() alone writes nothing; line.setOrder(order) is what sets the foreign key. Helper methods like addLine keep both sides in step.
  • A unidirectional @OneToMany without mappedBy uses a join table by default, which surprises people; add @JoinColumn to use a foreign key on the child table instead.
  • @OneToOne puts the foreign key on the owning side; make the inverse side lazy only if you accept that the provider may still have to query to know whether the target exists.
  • @ManyToMany uses a join table on both sides; @JoinTable names it. Once the join table needs its own columns (a date, a quantity) it is an entity of its own with two @ManyToOne associations.

Fetching

Defaults: @ManyToOne and @OneToOne are EAGER, collections are LAZY. The defaults are wrong for most applications in the eager direction: an eager many-to-one on every entity means every query drags in its customers, their addresses, and so on. Declare fetch = FetchType.LAZY on to-one associations and load what a use case needs explicitly with JOIN FETCH or an entity graph — both covered in the queries guide. Lazy loading works only while the context is open, which is why accessing order.getLines() in a view after the transaction ended throws LazyInitializationException on Hibernate. The N+1 problem is the mirror image: iterating a hundred orders and touching each getCustomer() issues a hundred extra selects. Both are fixed at the query, not by switching everything to eager.

Cascades and orphan removal

cascade propagates an EntityManager operation along an association: CascadeType.PERSIST on lines means persisting the order persists its new lines. ALL is appropriate for a composition — lines cannot exist without their order — and dangerous for anything shared: cascade = ALL on Order.customer would delete the customer when you remove an order. orphanRemoval = true additionally deletes a child when it is removed from the collection, which turns order.getLines().remove(line) into a DELETE. Together they let you treat an aggregate as one unit.

Inheritance and shared mappings

Entities can inherit from entities, and JPA offers three table layouts:

StrategyTablesTrade-off
SINGLE_TABLE (default)One table for the hierarchy with a discriminator columnFastest queries, no joins; subclass columns must be nullable
JOINEDOne table per class joined on the primary keyNormalised, nullable-free; every polymorphic query joins
TABLE_PER_CLASSOne complete table per concrete classNo joins for concrete queries; polymorphic queries need UNION, and identity generation is restricted

Declare the strategy with @Inheritance on the root and @DiscriminatorValue on subclasses. Often what you want is not entity inheritance but a @MappedSuperclass: a base class such as AuditedEntity with id, version, createdAt and updatedAt whose fields are mapped into each subclass's table but which is not itself queryable.

Optimistic locking with @Version

Two users load the same order, both change it, both save: without protection the second write silently overwrites the first — the lost update. A @Version field (a number or a timestamp) makes the provider add WHERE version = ? to every UPDATE and increment the version; if zero rows are affected, the row changed under you and OptimisticLockException is thrown at flush or commit. Every entity that can be edited concurrently should carry one. Carry the version through to the client (a hidden field in a form, a field in a JSON payload) and back into merge, otherwise the check compares the freshly loaded version with itself and protects nothing. Pessimistic locking — em.find(Order.class, id, LockModeType.PESSIMISTIC_WRITE), a SELECT … FOR UPDATE — is the alternative for short, contended updates such as stock decrements.

Providers and schema generation

Hibernate ORM 6.x and EclipseLink 4.x implement Persistence 3.1; both are bundled with the major servers (Hibernate in WildFly, EclipseLink in GlassFish and Payara, either in Open Liberty). Keep your code to the JPA API and you can switch; use provider extensions consciously — Hibernate's @BatchSize, @Formula, natural ids and its richer HQL are useful, but each is a portability cost.

The standard property jakarta.persistence.schema-generation.database.action (none, create, drop, drop-and-create) can generate tables from your mappings; Hibernate's own hibernate.hbm2ddl.auto adds update and validate. Generation is convenient for tests and prototypes and a poor way to run production: generated DDL lacks the constraints, index choices and migration history a real schema needs. Manage production schemas with versioned migration scripts (Flyway, Liquibase), set the standard property to none, and use Hibernate's validate if you want mappings checked against the real schema at start-up.

Common mistakes

  • Eager to-one associations everywhere. Every query loads a tree. Mark them LAZY and fetch per use case.
  • Touching lazy collections outside the transaction. LazyInitializationException in views and serialisers. Fetch in the query or map to DTOs inside the service.
  • Forgetting the owning side. Adding to the mappedBy collection writes nothing. Set the many-to-one, or use helper methods that do both.
  • EnumType.ORDINAL. Inserting a constant in the middle of the enum reinterprets every stored value. Use STRING.
  • cascade = ALL on shared entities. Removing an order deletes its customer. Cascade only along compositions.
  • hashCode based on a generated id. Changes after persist; entities disappear from sets. Use a business key or a stable UUID assigned in the constructor.
  • Mismatched allocationSize and sequence increment. Gaps at best, duplicate-key errors at worst. Keep them equal.
  • Schema generation in production. Missing constraints and no migration history. Use Flyway or Liquibase.

Key takeaways

  • A persistence unit defines the entities and the data source; a container-managed EntityManager gives you a persistence context scoped to the JTA transaction.
  • Entities are new, managed, detached or removed; managed entities are dirty-checked and written at flush, and merge returns the managed copy rather than attaching your object.
  • Map identifiers with SEQUENCE where the database allows; IDENTITY disables batching and UUID is standard since Persistence 3.1.
  • The owning side of an association holds the foreign key; keep both sides of bidirectional associations consistent with helper methods.
  • Make to-one associations lazy and fetch explicitly per use case; cascade and orphan removal only along compositions.
  • Use @MappedSuperclass for shared audit fields and entity inheritance only when the model is genuinely polymorphic.
  • Add @Version to editable entities and carry it through the UI or API to prevent lost updates.

Sources and further reading

Frequently asked questions

What is the difference between JPA and Hibernate?
JPA (Jakarta Persistence) is the specification: annotations, the EntityManager API, JPQL and the Criteria API. Hibernate ORM is the most widely used implementation of it, alongside EclipseLink, which is the compatible implementation used to certify the specification. Code written to the JPA API runs on either; Hibernate-specific annotations and Session methods do not. Since Hibernate 6 the two have converged further, with Hibernate's HQL being a superset of JPQL.
Why do I get LazyInitializationException?
You touched a lazy association after the persistence context that loaded the entity was closed — typically in a Faces page or a REST serialiser after the transaction ended. Fix it at the query: use a JOIN FETCH or an entity graph to load what the view needs inside the transaction, or map the result to a DTO before returning. Making everything EAGER is not a fix; it moves the cost to every query.
Should I use merge or persist to save an entity?
persist for a new object you created with new: it becomes managed and an INSERT is scheduled. merge for a detached object (one that came from an earlier transaction, a form, or a deserialised request): it copies the state onto a managed instance and returns that instance — the object you passed stays detached. Calling persist on a detached entity throws, and calling merge on a new entity works but issues an extra SELECT.
Do I need equals and hashCode on entities?
Only if you put entities in a Set or use them as map keys, which many-to-many and one-to-many Set mappings do. Base them on a business key or on the identifier once it is assigned, never on all fields, and never on a generated id before persist — the hash would change when the id is generated and the object would vanish from any HashSet it was already in.