Hibernate Interview Questions and Answers

Hibernate Interview Questions and Answers - EncodingCompiler

Quick answer

Hibernate is the most widely used Java ORM framework and JPA implementation: it maps Java classes to database tables and generates the SQL to load and save objects. Hibernate interviews focus on the Session and SessionFactory, entity states, lazy loading, first- and second-level caching, the N+1 select problem, and what changed in Hibernate 6.

Hibernate is the most widely used ORM framework for Java, and it shows up in almost every interview for a Java backend or Spring Boot role. Interviewers use it to test two things: whether you understand how objects map to tables, and whether you know what Hibernate is doing to your database behind the scenes. This guide covers the questions that come up most, from basics to the performance questions experienced candidates get.

Where an API has changed between versions, the answer says so. Many teams still run Hibernate 5, while newer projects use Hibernate 6 or later with Jakarta Persistence, and interviewers notice when you know the difference.

Hibernate Interview Questions and Answers for Freshers

Hibernate interview questions and answers: Hibernate Object States
Hibernate Object States (quick reference)

1. What is Hibernate?

Hibernate is an open-source object-relational mapping (ORM) framework for Java. It maps Java classes to database tables and Java objects to rows, so you work with objects in code and Hibernate generates the SQL to load and save them. Hibernate ORM is also the most widely used implementation of the Java Persistence API (JPA), now called Jakarta Persistence.

2. What is ORM?

Object-relational mapping is a technique for converting between objects in a program and rows in a relational database. Instead of writing SQL and copying result set columns into fields by hand, you describe the mapping once and the ORM handles the conversion in both directions.

3. What is the relationship between Hibernate and JPA?

JPA is a specification: a set of interfaces and annotations such as EntityManager, @Entity and @OneToMany. Hibernate is an implementation of that specification, and it also offers features beyond it. Writing code against the JPA interfaces keeps your application portable to other implementations, such as EclipseLink.

4. What are the advantages of Hibernate over JDBC?

  • Less boilerplate. No manual mapping of result sets to objects, and no hand-written insert and update statements for every entity.
  • Database portability. Hibernate generates SQL for the configured database dialect, so moving databases mostly means changing configuration.
  • Relationships handled for you. Associations between entities are loaded and saved through mappings rather than joins written by hand.
  • Caching. A first-level cache is built in, and a second-level cache can be added.
  • Exception translation. Checked SQLExceptions become unchecked, more specific exceptions.

It is worth adding that Hibernate does not remove the need to understand SQL. Interviewers like candidates who know that a poorly mapped entity can generate far more queries than hand-written JDBC would.

5. Name some Java ORM and persistence frameworks.

Full ORMs and JPA implementations include Hibernate, EclipseLink, Apache OpenJPA and DataNucleus. MyBatis is often mentioned alongside them, but it is a SQL mapper: you write the SQL and it maps the results to objects. Older options included EJB 2 entity beans and TopLink, which became EclipseLink.

6. Which databases does Hibernate support?

Most relational databases, including PostgreSQL, MySQL, MariaDB, Oracle, Microsoft SQL Server, IBM Db2, SAP HANA, H2 and HSQLDB. Support comes through dialects, described in question 22.

7. What is HQL?

HQL, the Hibernate Query Language, is an object-oriented query language. It looks like SQL but queries entities and their properties rather than tables and columns, for example from Employee e where e.department.name = :dept. Hibernate translates it into SQL for the configured database. JPQL, the JPA query language, is a subset of HQL.

8. What are the advantages of HQL?

  • Database independent: the same query runs on any supported database.
  • Works with entity relationships directly, so you navigate e.department.name rather than writing a join.
  • Supports polymorphic queries: querying a parent class also returns its subclasses.
  • Keywords are case-insensitive, although entity and property names are not.

9. What are the main components of the Hibernate architecture?

  • Configuration: reads settings and mappings and builds the SessionFactory.
  • SessionFactory: a heavyweight, thread-safe factory for sessions, usually one per database per application.
  • Session: a lightweight, short-lived unit of work that wraps a JDBC connection and holds the first-level cache.
  • Transaction: marks the boundaries of a unit of work.
  • Query: runs HQL or native SQL and returns results.

Below these sit JDBC and the database itself. In JPA terms, the SessionFactory corresponds to the EntityManagerFactory and the Session to the EntityManager.

10. What is the Hibernate configuration file?

hibernate.cfg.xml holds connection settings, the dialect, and other options, and lists the mapped classes. Hibernate reads it to build the SessionFactory. In Spring Boot applications, the same settings usually live in application.properties instead.

11. What is a persistent class?

A persistent class, or entity, is a Java class mapped to a database table, usually with @Entity. It needs an identifier property and a no-argument constructor. It should not be final if you want lazy loading, because Hibernate creates proxy subclasses of it.

12. What types of association does Hibernate support?

One-to-one, one-to-many, many-to-one and many-to-many. Each can be unidirectional, navigable from one side only, or bidirectional, navigable from both.

13. Explain one-to-one and many-to-one associations.

Many-to-one is the most common association: many employees belong to one department, so each employee row holds a foreign key to the department. One-to-one means each row relates to at most one row on the other side, such as a user and their profile. With annotations it is mapped with @OneToOne. In older XML mappings, it was often written as a many-to-one with a unique constraint on the foreign key.

14. Explain one-to-many and many-to-many associations.

One-to-many is the other side of many-to-one: one department has a collection of employees, mapped with @OneToMany, usually as a List or Set. Many-to-many, such as students and courses, cannot be held by a foreign key on either table, so it needs a join table holding pairs of keys, mapped with @ManyToMany and @JoinTable.

15. What is a mapping file?

Before annotations, mappings were written in XML files, conventionally named ClassName.hbm.xml. Their main elements are hibernate-mapping (the root), class (the entity and its table), id and generator (the primary key and how it is generated) and property (a field and its column). Most projects now use annotations, but you will still see these files in older codebases.

Intermediate Hibernate Interview Questions

Hibernate interview questions and answers: get() vs load() / getReference()
get() vs load() / getReference() (quick reference)

16. Is SessionFactory thread-safe?

Yes. It is immutable once built, so many threads can share one instance and open sessions from it. Because it is expensive to create, applications usually build one at startup and keep it.

17. Is Session thread-safe?

No. A session holds mutable state, including its cache and the connection, so each thread or request should open its own session and close it when the work is done.

18. What is the Hibernate Session used for?

The session is the main interface for working with the database. You use it to save, load, update and delete entities, run queries, and manage transactions. It also tracks every entity it has loaded, so changes made to those objects are written to the database automatically when the session flushes.

19. How do you create HQL and native SQL queries?

Use session.createQuery() for HQL. For native SQL, Hibernate 5 used session.createSQLQuery(), which was deprecated and removed in Hibernate 6 in favor of session.createNativeQuery(). With JPA, the equivalents are entityManager.createQuery() and entityManager.createNativeQuery().

20. What are the common Query methods?

  • setParameter() binds a named or positional parameter.
  • getResultList() (or list() in older versions) returns all results.
  • getSingleResult() or uniqueResult() returns exactly one result.
  • setFirstResult() and setMaxResults() paginate.
  • executeUpdate() runs a bulk update or delete.

21. What is the Criteria API?

The Criteria API builds queries in Java code rather than as strings, which suits queries assembled at runtime, such as a search screen with optional filters. Hibernate’s own legacy Criteria API was deprecated in Hibernate 5.2 and removed in 6. The JPA Criteria API, started from CriteriaBuilder, is the one to use now.

22. What is a Hibernate dialect?

A dialect tells Hibernate which database it is talking to, so it can generate the right SQL for that database’s types, functions and syntax, such as how to paginate. Recent Hibernate versions usually detect the dialect automatically from the JDBC connection.

23. What is lazy loading?

Lazy loading means an associated entity or collection is not fetched until your code first uses it. Hibernate returns a proxy, and the query runs when you touch it. This avoids loading large object graphs you do not need. Watch the defaults: in JPA, collection associations are lazy, but @ManyToOne and @OneToOne are eager unless you set fetch = FetchType.LAZY.

24. What is a LazyInitializationException?

It is thrown when code touches a lazy association after the session that loaded the entity has closed, so there is no connection left to fetch it with. The fix is to fetch what you need while the session is open, with a fetch join or an entity graph, rather than keeping sessions open longer.

25. What is Hibernate caching, and what types are there?

  • First-level cache: belongs to the session and is always on. Loading the same entity twice in one session hits the database once.
  • Second-level cache: belongs to the SessionFactory, so it is shared across sessions. It is optional and needs a provider such as Ehcache, Infinispan or another JCache implementation. Hibernate checks the first-level cache, then the second-level cache, then the database.
  • Query cache: stores the IDs returned by a query for a given set of parameters. It only helps alongside the second-level cache, and only for queries repeated often with the same parameters on data that rarely changes.

26. What is the difference between the first-level and second-level cache?

The first-level cache is scoped to one session, enabled by default, and cannot be turned off. The second-level cache is scoped to the SessionFactory, shared by all sessions, disabled by default, and has to be configured per entity.

27. What are the second-level cache concurrency strategies?

  • Read-only: for data that never changes, such as reference tables. The fastest option.
  • Nonstrict read-write: for data that changes rarely, where briefly reading a stale value is acceptable.
  • Read-write: for data that is updated and must stay consistent. It uses soft locks to stop other transactions reading stale data.
  • Transactional: full transactional caching, for JTA environments with a transactional cache provider.

28. How do you map a composite primary key?

Create a key class that is public, implements Serializable, has a no-argument constructor, and implements equals() and hashCode(). Then map it in one of two ways: @EmbeddedId with an @Embeddable key class, or @IdClass with the key fields repeated on the entity.

@Embeddable
public class OrderLineId implements Serializable {
    private Long orderId;
    private Integer lineNumber;
    // equals() and hashCode()
}

@Entity
public class OrderLine {
    @EmbeddedId
    private OrderLineId id;
}

Hibernate Interview Questions for Experienced Developers

Hibernate interview questions and answers: First-Level vs Second-Level Cache
First-Level vs Second-Level Cache (quick reference)

29. What are the entity states in Hibernate?

  • Transient: just created with new, not associated with any session and not in the database.
  • Persistent (managed): associated with an open session. Changes are tracked and written on flush.
  • Detached: was persistent, but its session has closed. Changes are no longer tracked until it is reattached, usually with merge().
  • Removed: scheduled for deletion, which happens when the session flushes.

30. What is the difference between get() and load()?

get() hits the database straight away and returns null if the row does not exist. load() returns a proxy without querying, and throws an exception later, when you first use the proxy, if the row does not exist. Use load(), or getReference() in JPA and newer Hibernate, when you only need a reference to set a foreign key.

31. What does merge() do?

merge() copies the state of a detached object onto a managed instance with the same ID, loading it first if needed, and returns that managed instance. The object you passed in stays detached. A common mistake is to keep using the original object and wonder why later changes are not saved.

32. What is the difference between save(), persist() and saveOrUpdate()?

persist() is the JPA method: it makes a transient entity managed and returns nothing. save() did the same but returned the generated ID, and saveOrUpdate() chose between insert and update. Both save() and saveOrUpdate() were deprecated in Hibernate 6 in favor of persist() and merge().

33. What is dirty checking?

When a session flushes, Hibernate compares each managed entity with the snapshot it took when the entity was loaded, and issues an update for anything that changed. That is why you do not need to call an update method on a managed entity: changing its fields inside a transaction is enough.

34. What is the N+1 select problem, and how do you fix it?

It happens when you load a list of N entities with one query, then touch a lazy association on each one, which triggers another query per entity: N+1 queries in total. Loading 100 orders and reading each order’s customer can produce 101 queries. Fixes include a fetch join, an entity graph, or batch fetching:

select o from Order o join fetch o.customer

Turning on SQL logging in development is the quickest way to spot it.

35. What are the inheritance mapping strategies?

  • Single table (table per hierarchy): all classes in one table with a discriminator column. The fastest to query, but subclass columns must allow nulls.
  • Joined (table per subclass): a table for the parent and one per subclass, joined on the primary key. Normalized, but every query needs joins.
  • Table per class (table per concrete class): a full table for each concrete class. Polymorphic queries need unions, so it is the least used.

36. How do you make an entity immutable?

Annotate it with @Immutable, or set mutable="false" in XML mappings. Hibernate then skips dirty checking for it and never issues updates, which suits reference data and read-only views.

37. Can a one-to-one or many-to-one association be a collection mapping?

No. Those associations point to a single entity. Collection mappings are only used for one-to-many and many-to-many associations, and for element collections of simple values.

38. What collection types can Hibernate map?

Set, List, Map, bag and array. A bag is an unordered collection that allows duplicates, and is how Hibernate treats a List that has no order column. Hibernate replaces your collection with its own persistent wrapper when it loads the entity, which is how it tracks changes and loads lazily.

39. How can you write joins in Hibernate?

Through mapped associations that Hibernate joins for you, with explicit join or join fetch in HQL, through the Criteria API, or with native SQL. Since Hibernate 6, HQL can also join entities that have no mapped association between them.

40. Can Hibernate run native SQL, and when should you?

Yes, with createNativeQuery(). Results can still be mapped to entities. Use native SQL for database-specific features HQL does not express, such as window functions or vendor hints. The trade-off is that the query is tied to one database, and Hibernate cannot always tell which cached data the query affects.

41. What are named queries, and why use them?

A named query is defined once, with a name, using @NamedQuery for HQL or @NamedNativeQuery for SQL, and then called by name. Named HQL queries are parsed when the SessionFactory starts, so a syntax error fails the application at startup rather than in production. They also keep queries in one place.

42. What is cascading, and what cascade types are there?

Cascading passes an operation from one entity to its associated entities, so saving an order can also save its order lines. The JPA cascade types are:

  • PERSIST: persisting the parent persists the children.
  • MERGE: merging the parent merges the children.
  • REMOVE: deleting the parent deletes the children.
  • REFRESH: refreshing the parent reloads the children.
  • DETACH: detaching the parent detaches the children.
  • ALL: all of the above.

Be careful with REMOVE on many-to-many or many-to-one associations, where the children are shared with other entities.

43. What is Hibernate Validator?

Hibernate Validator is the reference implementation of Bean Validation, the specification once known as JSR 303, 349 and 380 and now called Jakarta Validation. You declare constraints with annotations such as @NotNull, @Size and @Email, and they are checked automatically before an entity is saved, as well as in frameworks such as Spring MVC.

Conclusion

Strong Hibernate answers come back to the same point: knowing what SQL your mappings produce. If you can explain entity states, lazy loading, caching and the N+1 problem clearly, you will handle most of what an interviewer asks. If you were asked a Hibernate question recently that is not listed here, share it in the comments and we can work through the answer together.

Sources and further reading

Comments

One response to “Hibernate Interview Questions and Answers”

  1. […] 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. […]

Leave a Reply

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