JPA Interview Questions and Answers

JPA Interview Questions and Answers - EncodingCompiler

Quick answer

JPA, now called Jakarta Persistence, is the standard Java specification for mapping objects to relational database tables, and Hibernate is its most widely used implementation. JPA interviews focus on entities and their lifecycle states, the EntityManager and persistence context, JPQL and the Criteria API, fetch types, ID generation strategies, and optimistic locking with @Version.

JPA questions come up in almost every Java backend interview, especially for Spring Boot roles, where Spring Data JPA is the default way to work with a database. This guide covers the questions asked most often, from what JPA is to identifier generation, locking and the persistence context, with short answers and examples.

JPA is a specification, and most of its real-world behavior comes from the implementation you run underneath it, usually Hibernate. For the Hibernate-specific side, such as caching, the N+1 problem and dirty checking, see our Hibernate interview questions.

JPA Interview Questions and Answers for Freshers

JPA interview questions and answers: JPA vs Hibernate
JPA vs Hibernate (quick reference)

1. What is JPA?

JPA, the Java Persistence API, is the standard specification for mapping Java objects to relational database tables and managing them. It defines the annotations, such as @Entity, @Id and @OneToMany, the EntityManager API, and the JPQL query language. JPA itself is only a set of interfaces and rules. To use it, you need an implementation, called a persistence provider.

2. What is Jakarta Persistence?

It is JPA’s current name. When Oracle handed Java EE to the Eclipse Foundation, it became Jakarta EE, and JPA became Jakarta Persistence. From version 3.0 the package changed from javax.persistence to jakarta.persistence. That is why upgrading to Spring Boot 3 or Hibernate 6 means changing your imports.

3. What is object-relational mapping?

Object-relational mapping (ORM) is a technique for converting between objects in code and rows in a relational database. A class maps to a table, a field maps to a column, and an object reference maps to a foreign key. You describe the mapping once, and the ORM writes the SQL to load and save objects.

4. What is the difference between JPA and Hibernate?

JPA is the specification. Hibernate is an implementation of it, the most widely used one, and it adds features beyond the specification. If your code uses only JPA interfaces and annotations, you can in principle switch to another provider. If you use Hibernate-specific features, you are tied to Hibernate.

5. Does JPA itself store or retrieve data?

No. JPA only defines how persistence should work. The provider does the work: it generates the SQL, talks to the database through JDBC, and tracks the objects.

6. What are the main JPA providers?

  • Hibernate ORM: the most widely used, and the default in Spring Boot.
  • EclipseLink: the reference implementation, which grew out of Oracle’s TopLink.
  • Apache OpenJPA and DataNucleus, which grew out of JPOX.

Some lists also include iBATIS, now MyBatis, or JDO. Neither is a JPA implementation. MyBatis is a SQL mapper, and JDO is a separate persistence specification.

7. What are the advantages of JPA?

  • A standard API, so knowledge and code carry across providers and projects.
  • Far less boilerplate than JDBC: no manual mapping of result sets to objects.
  • Mappings are declared with annotations on the class, beside the code that uses them.
  • Portable queries with JPQL, which the provider translates for each database.
  • Relationships, cascading and change tracking are handled for you.

8. What is an entity?

An entity is a Java class whose instances are stored as rows in a database table. You mark it with @Entity and give it a primary key field marked with @Id.

@Entity
@Table(name = "customers")
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    protected Customer() { }   // required by JPA

    public Customer(String name) { this.name = name; }
}

9. What are the requirements for an entity class?

  • It must be annotated with @Entity.
  • It must have a public or protected no-argument constructor.
  • It must have a primary key, marked with @Id or @EmbeddedId.
  • The class, and its persistent methods and fields, must not be final, so the provider can create proxies for lazy loading.
  • It must be a top-level class, not an enum or interface.

Implementing Serializable is only required if instances are passed by value, for example sent to a remote client as detached objects.

10. What are the core classes and interfaces of the JPA API?

  • Persistence: a bootstrap class with static methods to create an EntityManagerFactory outside a container.
  • EntityManagerFactory: created once per persistence unit, thread-safe, and expensive to build. It creates entity managers.
  • EntityManager: the main API for saving, finding, updating and removing entities and creating queries. Not thread-safe, and short-lived.
  • EntityTransaction: controls transactions when you manage them yourself, outside a container or Spring.
  • Query and TypedQuery: run JPQL or native SQL and return results.
  • CriteriaBuilder: builds queries in code with the Criteria API.

11. What is persistence.xml?

persistence.xml, in META-INF, defines one or more persistence units: the provider, the database connection, the entity classes, and provider settings. In Spring Boot, you usually do not need it, since the same settings go in application.properties.

12. What is JPQL?

JPQL, the Java Persistence Query Language, queries entities rather than tables. It looks like SQL, but you refer to entity names and fields, and you navigate relationships with dots:

TypedQuery<Order> q = em.createQuery(
    "select o from Order o where o.customer.name = :name", Order.class);
q.setParameter("name", "Asha");
List<Order> orders = q.getResultList();

The provider translates JPQL into SQL for the configured database. It supports select, update and delete. Inserts are done by persisting entities.

13. What are the features of JPQL?

  • Database independent: the same query works on any supported database.
  • Works with entities and their relationships, so most joins need no join condition.
  • Supports named parameters (:name) and positional parameters (?1), which also protect against SQL injection.
  • Queries can be written inline in code, or declared once as named queries with @NamedQuery.
  • Supports aggregates, grouping, subqueries, and constructor expressions that return DTOs directly.

14. What are the entity lifecycle states?

  • New (transient): created with new, not yet associated with a persistence context or saved.
  • Managed: associated with a persistence context. Changes are tracked and written to the database when the transaction commits or the context flushes.
  • Detached: was managed, but its persistence context has closed. Changes are not saved unless you pass it to merge().
  • Removed: scheduled for deletion, which happens on flush or commit.

JPA Interview Questions for Experienced Developers

JPA interview questions and answers: JPA Entity Lifecycle
JPA Entity Lifecycle (quick reference)

15. What is the persistence context?

The persistence context is the set of managed entities an EntityManager is tracking. Within one context, each database row is represented by exactly one object, so finding the same entity twice returns the same instance. On flush, the provider compares managed entities with their original state and writes any changes. In Spring, the persistence context normally lasts for one transaction.

16. What does the EntityManager do?

  • persist() makes a new entity managed, so it is inserted on flush.
  • find() loads an entity by primary key.
  • merge() copies a detached entity’s state onto a managed instance and returns it.
  • remove() schedules a managed entity for deletion.
  • refresh() reloads an entity from the database, discarding unsaved changes.
  • flush() writes pending changes now, rather than at commit.
  • createQuery() and createNativeQuery() build queries.

17. What is the difference between find() and getReference()?

find() queries the database straight away and returns null if the row does not exist. getReference() returns a lazy proxy without querying, and throws EntityNotFoundException later, when you first use it, if the row does not exist. getReference() is useful when you only need to set a foreign key, for example assigning an existing customer to a new order without loading the customer.

18. What is the difference between persist() and merge()?

persist() takes a new entity and makes that same object managed. It returns nothing. merge() takes an entity in any state, copies its state onto a managed instance, loading one if needed, and returns that managed instance. The object you passed in stays as it was. After a merge, always use the returned object.

19. What are the identifier generation strategies?

Set with @GeneratedValue(strategy = ...):

  • IDENTITY: the database generates the key with an auto-increment column. Simple, but the provider must insert the row immediately to learn the ID, which in Hibernate prevents batched inserts.
  • SEQUENCE: uses a database sequence, customized with @SequenceGenerator. Efficient, because the provider can fetch a block of IDs at once. The usual choice on PostgreSQL and Oracle.
  • TABLE: simulates a sequence with a separate table. Portable but slow, and rarely recommended.
  • UUID: generates a UUID, added in JPA 3.1.
  • AUTO: the default. The provider chooses, and the choice can differ between providers and versions, so it is better to choose explicitly.

20. What is the Criteria API?

The Criteria API builds queries with Java objects rather than strings. It is more verbose than JPQL, but it suits queries assembled at runtime, such as a search screen with optional filters, and with the generated metamodel it is type-safe, so a misspelled field name fails at compile time.

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);
Root<Customer> c = cq.from(Customer.class);
cq.select(c).where(cb.equal(c.get("city"), "Pune"));
List<Customer> result = em.createQuery(cq).getResultList();

21. What are the fetch types, and what are their defaults?

FetchType.EAGER loads the association with the entity. FetchType.LAZY loads it only when first used. The defaults are a common interview trap: @OneToMany and @ManyToMany are lazy, but @ManyToOne and @OneToOne are eager. Most teams make every association lazy and fetch what each query needs explicitly, with join fetch or an entity graph.

22. What is an entity graph?

An entity graph tells the provider which associations to load for a particular query, overriding the mapping’s fetch type for that query only. You define it with @NamedEntityGraph or build it in code, and pass it as a query hint. It is a clean way to avoid both lazy loading errors and the N+1 problem.

23. How does optimistic locking work in JPA?

Add a field annotated with @Version. Each update checks that the version in the database still matches the one that was read, and increments it. If another transaction updated the row in the meantime, the update matches no rows and the provider throws an OptimisticLockException. It prevents lost updates without holding database locks. For pessimistic locking, pass a lock mode such as LockModeType.PESSIMISTIC_WRITE, which issues select ... for update.

24. What can be stored in a collection mapping?

  • Entities, through @OneToMany and @ManyToMany associations.
  • Basic types, such as a set of strings for tags, through @ElementCollection, stored in a separate table.
  • Embeddables, such as a list of addresses, also through @ElementCollection.

The collection types you can use are Collection, List, Set and Map.

25. What is an embeddable?

An embeddable, marked @Embeddable, is a class with no identity of its own whose fields are stored in the owning entity’s table. An Address class embedded in Customer with @Embedded becomes street, city and postcode columns in the customers table. It is the JPA way to model value objects.

26. What is orphan removal?

Setting orphanRemoval = true on a @OneToMany or @OneToOne association deletes a child from the database when it is removed from the parent’s collection or reference. Removing an order line from order.getLines() deletes that line.

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

Compare it with CascadeType.REMOVE, which only deletes children when the parent itself is deleted.

27. What does mappedBy mean?

In a bidirectional relationship, one side owns the foreign key and the other side mirrors it. mappedBy goes on the side that does not own it and names the field on the owning side. In an order and order-lines relationship, the line holds the foreign key, so the order’s collection uses mappedBy = "order". Changes saved to the database come from the owning side, so you should set both sides in code to keep your objects consistent.

28. How does Spring Data JPA relate to JPA?

Spring Data JPA sits on top of JPA. You declare a repository interface, such as interface CustomerRepository extends JpaRepository<Customer, Long>, and Spring generates the implementation, including queries derived from method names like findByCity(String city). Underneath, it still uses an EntityManager and your JPA provider, which is why JPA knowledge matters even when you rarely write JPA code directly.

JPA interview questions and answers: JPA Default Fetch Types
JPA Default Fetch Types (quick reference)

Conclusion

Most JPA interviews come back to the same few ideas: the persistence context and entity states, how fetching works, and how IDs and locking are handled. If you can explain those, and the line between JPA the specification and Hibernate the implementation, you will be well prepared. If you were asked a JPA question recently that is not here, share it in the comments and we can work through it together.

Sources and further reading

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *