JPA interview questions and answers for Java backend roles

JPA interview questions focus on the specification itself: what the EntityManager does, how the persistence context tracks entities, how to map relationships with a correct owning side, and how JPQL differs from SQL. Interviewers also check Spring Data JPA habits, such as what save really calls and how derived queries are built. Strong answers separate what the JPA standard promises from what a provider such as Hibernate adds.

By Published 7 min read

What JPA interviews actually probe

JPA questions come up in nearly every Java backend loop that uses Spring Boot, and they also appear in enterprise roles on Jakarta EE servers. The interviewer wants to know whether your mental model matches what the framework does with your objects. A candidate who can say exactly when SQL is sent, and which side of a relationship writes the foreign key, is trusted with the data layer. Performance tuning in Hibernate, such as N+1 fixes and second-level caching, has a separate page: Hibernate interview questions.

  1. Spec and vocabularyEntity, persistence unit, persistence context, provider, managed versus detached.
  2. Mapping exerciseModel two or three related tables as entities on a whiteboard or in an editor, with keys and relationships.
  3. Behavior questionsWhat SQL runs after this code? Why did this change not save? Why did this delete remove more than expected?
  4. Spring Data and designRepositories, query methods, projections, transactions and where JPA stops being the right tool.

JPA fundamentals questions

Concept questions for freshers and early screens
QuestionWhat it testsWhat a strong answer shows
What is JPA, and is Hibernate the same thing?Spec versus providerJPA is a specification for object-relational mapping in Java. Hibernate ORM is the most common provider; EclipseLink and OpenJPA are others. Code written against the JPA API can, in principle, switch providers.
Why did imports change from javax.persistence to jakarta.persistence?EcosystemJava EE moved to the Eclipse Foundation as Jakarta EE, and the package namespace was renamed. Spring Boot 3 and recent providers use the jakarta packages, which is a common migration task.
What makes a class an entity?Basics@Entity, a primary key marked @Id, and a no-argument constructor that is public or protected. The class should not be final, so providers can create proxies for lazy loading.
What is a persistence unit?ConfigurationA named set of entity classes plus datasource and provider settings, declared in persistence.xml or built by a framework such as Spring Boot from properties.
EntityManagerFactory versus EntityManager?LifecycleThe factory is expensive, thread-safe and created once per persistence unit. An EntityManager is cheap, not thread-safe and lives for one unit of work, usually a transaction.
What is the persistence context?Core modelThe set of managed entity instances an EntityManager tracks, at most one instance per database identity. It acts as a first-level cache and is where changes are detected before flushing.
What are the entity states?LifecycleNew (transient), managed, detached and removed. Only managed entities have their changes written automatically.
What does @GeneratedValue support?KeysAUTO, IDENTITY, SEQUENCE and TABLE, with UUID added in recent spec versions. IDENTITY forces an immediate insert to learn the key, which limits batching; SEQUENCE does not.
What does @Transient do?MappingExcludes a field from persistence. It is not the same as the Java transient keyword, which affects serialization.
Why is EnumType.ORDINAL risky?Mapping trapIt stores the enum position, so reordering or inserting a constant silently changes the meaning of existing rows. Use EnumType.STRING or a converter with stable codes.
Concept questions for freshers and early screens. Scroll sideways on a small screen.

EntityManager and persistence context questions

  • persist versus merge? persist makes the instance you pass managed and schedules an insert; it fails for a detached entity. merge copies the state of the given object onto a managed instance (loading or creating it) and returns that managed instance. The argument stays detached, so keep using the return value.
  • find versus getReference? find hits the persistence context, then the database, and returns null if the row is missing. getReference may return an uninitialized proxy without a query, which is handy for setting a foreign key, and throws EntityNotFoundException only when the proxy is first used and the row is missing.
  • You load an entity, change a field and never call save. Is it updated? Yes, if the entity is managed inside an active transaction. At flush, the provider compares it with its loaded state and issues an UPDATE.
  • When does a flush happen? Before commit, when flush is called, and in the default AUTO mode before a query whose results could be affected by pending changes. FlushModeType.COMMIT delays it to commit.
  • What do clear and detach do? clear detaches everything in the persistence context; detach does it for one entity. Pending, unflushed changes to those entities are discarded, so flush first if you need them.
  • Why can a bulk JPQL UPDATE leave stale data? Bulk statements go straight to the database and bypass the persistence context. Already-loaded entities keep their old values until you clear or refresh them.
  • Is an injected EntityManager thread-safe in Spring? The injected object is a shared proxy that routes each call to the EntityManager bound to the current transaction, so injecting it into a singleton is safe. The underlying EntityManager itself is not thread-safe.
  • What are lifecycle callbacks? Methods annotated with @PrePersist, @PostPersist, @PreUpdate, @PostLoad and similar, on the entity or in an @EntityListeners class, often used for audit timestamps.

Mapping and relationship questions

@Entity
public class PurchaseOrder {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @Enumerated(EnumType.STRING)
    private OrderStatus status;

    @Embedded
    private Address shipTo;

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

    @Version
    private int version;

    public void addLine(OrderLine line) {   // keep both sides in sync
        lines.add(line);
        line.setOrder(this);
    }

    public void removeLine(OrderLine line) {
        lines.remove(line);
        line.setOrder(null);
    }
}

@Entity
public class OrderLine {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "order_id")
    private PurchaseOrder order;          // owning side: writes order_id

    private String sku;
    private int quantity;

    void setOrder(PurchaseOrder order) { this.order = order; }
}
A bidirectional one-to-many with the foreign key on the child. Not executed: it needs a JPA provider and a database.
Mapping questions interviewers build on a model like the one above
QuestionWhat it testsWhat a strong answer shows
What is the owning side of a relationship?Foreign keysThe side whose mapping controls the join column or join table. In a one-to-many pair it is the @ManyToOne. mappedBy marks the inverse side, whose changes alone are not written.
You add a line to order.getLines() but order_id stays null. Why?Bidirectional syncOnly the inverse side was changed. Set line.setOrder(order) too, ideally through helper methods like addLine that update both sides.
What are the default fetch types?LoadingTo-one associations default to EAGER, to-many default to LAZY. Many teams make every association LAZY and fetch explicitly per query.
CascadeType.REMOVE versus orphanRemoval?DeletesCascade REMOVE deletes children when the parent is removed. orphanRemoval also deletes a child that is merely taken out of the collection. Never cascade REMOVE on a many-to-one; it can delete a shared parent.
How do you map a many-to-many with extra columns?ModelingTurn the join table into its own entity with two many-to-one relationships, for example Enrollment between Student and Course with a grade column.
Which inheritance strategies exist?InheritanceSINGLE_TABLE (one table and a discriminator, fastest, nullable subclass columns), JOINED (normalized, needs joins) and TABLE_PER_CLASS (a table per concrete class, painful polymorphic queries). @MappedSuperclass shares fields without being an entity.
@Embeddable or a separate entity?Value objectsEmbeddable for values with no identity of their own, like an address or money amount, stored in the owner's table. An entity when it has its own lifecycle or is shared.
How do you store a custom type?ConvertersAn AttributeConverter maps it to a basic column type, for example a Money value to an integer of minor units, applied with @Convert or automatically.
How should entities implement equals and hashCode?IdentityNot on a generated ID that is null before persist, or the object changes buckets in a HashSet. Use a stable business key, or ID-based equals with a constant hashCode.
What does @Version give you?ConcurrencyOptimistic locking: the version is checked and incremented on update, and a stale write fails with an OptimisticLockException. Lock types are covered further on the Hibernate page.
Mapping questions interviewers build on a model like the one above. Scroll sideways on a small screen.

JPQL, Criteria and Spring Data JPA questions

  • How is JPQL different from SQL? It queries entities and their fields, not tables and columns, and navigates relationships with paths such as o.shipTo.city. The provider translates it into SQL for the configured dialect.
  • When would you use the Criteria API? For queries assembled at runtime, such as search screens with optional filters, where string building would be fragile. For fixed queries, JPQL is easier to read.
  • How do you return a DTO instead of entities? A constructor expression (SELECT new com.shop.OrderSummary(o.id, o.status) FROM PurchaseOrder o), or in Spring Data an interface or class-based projection. DTOs avoid loading and tracking full entities for read-only screens.
  • What does Spring Data's save actually call? If the entity is considered new (by default, a null ID or null version) it calls persist, otherwise merge. With assigned IDs, save may run an extra SELECT for that reason.
  • How are derived query methods built? Spring Data parses names like findByCustomerEmailAndStatusOrderByCreatedAtDesc into a query at startup, so a typo fails at boot. Long names are a sign to switch to @Query.
  • Why does an @Query that updates need @Modifying? It tells Spring Data to run executeUpdate instead of a select. Add clearAutomatically = true when stale managed entities could be read afterwards, and run it inside a transaction.
  • How do you paginate? Pass a Pageable and get a Page with the total count, or a Slice to skip the count query. For deep pages on large tables, keyset pagination on an indexed column is faster than offsets.
  • When should you not use JPA? Heavy reporting, bulk data movement and highly tuned SQL. Plain SQL or a query builder is clearer there, see JDBC interview questions.

Senior and scenario questions

Scenarios to talk through
ScenarioLikely causeWhat to say you would check
Changes made in a service method are never saved.No transaction or detached entityWhether the method runs inside a transaction at all (self-invocation skips Spring's proxy), and whether the entity was loaded in an earlier transaction and is now detached.
Saving an order deletes and reinserts every line.Collection replacedCode that assigns a new list to the field instead of modifying the managed collection, combined with orphanRemoval. Mutate the existing collection.
Deleting a customer fails with a constraint error.Missing cascade or referenceOther tables still reference the row. Decide explicitly: cascade, soft delete, or block the delete with a clear message.
A new enum constant corrupted historical data.Ordinal mappingLook for EnumType.ORDINAL and migrate to string values with a data migration script.
Equal orders disappear from a HashSet after saving.hashCode on generated IDhashCode changed when persist assigned the ID. Use a stable key or a constant hashCode.
Schema drifts between environments.Auto DDL in useGenerating the schema from entities in production. Use migrations (Flyway or Liquibase) and validate the mapping against the schema at startup.
Scenarios to talk through. Scroll sideways on a small screen.

Fictional example

Answering "Why is order_id null after I add a line?"
Interviewer
A teammate calls order.getLines().add(line) and saves the order. The line row is inserted, but order_id is null. What happened?
Candidate
The collection on PurchaseOrder is the inverse side because it uses mappedBy, so JPA ignores it when deciding the foreign key. The owning side is the order field on OrderLine, and nobody set it. The insert comes from the cascade, so the line is saved, just without its parent. I would fix it with an addLine helper on the order that adds to the list and sets line.order in one place, and make the collection getter return an unmodifiable view so nobody bypasses the helper. Then I would add a repository test that saves an order with two lines and asserts the foreign key on reload.

JPA practice plan

  • Day 1: map three tables (customer, order, order line) by hand, choosing the owning side, fetch types and cascades, and explain each choice aloud.
  • Day 2: in a small Spring Boot project with SQL logging on, run persist, merge, find and getReference and note which statements appear and when.
  • Day 3: reproduce the null foreign key, the stale bulk update and the ordinal enum bug, then fix each.
  • Day 4: write the same search as JPQL, Criteria and a Spring Data derived method, and return a projection instead of entities.
  • Day 5: read the Hibernate interview questions page for fetch and locking depth, and rehearse the scenario table.

Mapping answers get long, and long answers drift. Natively, an AI interview assistant for Mac and Windows, transcribes a mock JPA round on your computer, so you can reread whether you named the owning side before wandering into fetch strategies. In practice it can read an entity class from a screenshot and suggest what to point out, and with Pro or the free trial it considers your résumé and the job description you add. The transcript and notes remain for later review.

Questions people ask

What JPA questions are asked in interviews?

JPA versus Hibernate, entity states, persist versus merge, find versus getReference, the persistence context and flushing, owning side and mappedBy, cascade types, inheritance strategies, JPQL and Spring Data repositories.

What is the difference between JPA and Hibernate?

JPA is the Java specification for object-relational mapping, now Jakarta Persistence. Hibernate ORM is a provider that implements it and adds its own features.

What is the owning side of a JPA relationship?

The side whose mapping controls the foreign key or join table, usually the @ManyToOne. The inverse side uses mappedBy and its changes alone are not written to the database.

What does Spring Data JPA save do?

It calls persist when the entity is considered new, by default when its ID or version is null, and merge otherwise.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP