Hibernate Interview Questions- Part 3

Hibernate Interview Questions- Part 3
Hibernate has earned its place as a foundational ORM tool in the Java ecosystem. But recruiters aren’t just looking for textbook answers—they want insight, clarity, and practical experience. This page dives deep into Hibernate interview questions that reveal your true understanding: session management, caching, annotations, HQL, and beyond.

Whether you’re refreshing your knowledge or prepping for your first tech interview, these questions will help you articulate your answers with precision. We’ve broken them down into digestible answers that reflect both conceptual depth and real-world relevance.

Answer:

Though both save() & saveOrUpdate() methods are used to store an object in the database, their key difference is that save() can only Insert records; however, saveOrUpdate() can either Update or Insert records.

The further differences between the methods are listed below:

save() saveOrUpdate()
The save() method generates a new identifier & INSERT record into the database. The saveOrUpdate() can either UPDATE or INSERT based on the existence of a record.
In the save() method, the insertion fails if the primary key already exists in the table. In the saveorUpdate() method, if the primary key already exists, the record is updated.
The return type of save() method is Serializable. The return type of the saveOrUpdate() method is void.
The save() method helps to bring a transient object to a persistent state. The saveOrUpdate() method can bring both transient (new) & detached (existing) objects into a persistent state. It is used to re-attach a detached object into the Session.

Answer:

The differences are as follows:

Parameter Sorted Collection Ordered Collection
Sorting The sorted collection utilizes Java’s sorting API to sort the collection. The ordered collection utilizes order by clause during the retrieval of objects.
Default The sorted collection is enabled by default. The ordered collection is not enabled by default; you have to enable it explicitly.

Answer:

  • Managed Associations: 
    • These associations are bi-directional and are related to container management persistence.
    • The Managed Association depicts the relationship between classes. If any change is made to one end of an association, it will be reflected at the other end. So, when any changes are made to the association’s attributes, they will automatically reflect at the end. The developer doesn’t have to manage the association manually.
  • Hibernate Associations: 
    • These associations are unidirectional.
    • If any table could be connected to other tables in the same or the other DB. Those tables could be associated with each other by some key. That type of scenario can be handled with the Hibernate association.

Answer:

Persistence means object & process characteristics that continue to exist even after the machine running on is disabled or the process that has created the object ceases. When a state or object is created & needs to be persistent, it is saved in a non-volatile storage location, such as a hard drive, versus a temporary file or volatile RAM.

Answer:

Hibernate has four ORM levels which are as follows:

    • Pure Relational ORM: The entire application is designed around the SQL-based operation & relational model at this level.
    • Light Object Mapping: At this level, the entities depict all the classes mapped manually to the relational tables. The applications with less no. of entities use this level.
    • Medium Object Mapping: At this level, an application is designed around the object model. Most SQL code is generated during the compile time. The persistence mechanism supports associations between the objects. The object-oriented expression is used to specify the queries.
    • Full Object Mapping: It is one of the most sophisticated object modelling levels. The Full Object Mapping supports inheritance, composition, persistence, & polymorphism. At this level, the persistent classes do not inherit the special base class.

Answer:

Below is the core interface of Hibernate:

    • SessionFactory (org.hibernate.SessionFactory)- The SessionFactory is an immutable thread-safe cache of compiled mappings meant for a single database. After initialising SessionFactory, it can be reused & cached. It is designed for returning the session objects for database operations.
    • Session (org.hibernate.Session)- It is a short-lived, single-threaded object that showcases a dialogue between the application & the persistent store. It is an interface between the Hibernate & Java application code, providing methods for CRUD operations.
    • Transaction (org.hibernate.transaction)- It is a single-threaded, short-lived object that an application uses to specify the atomic units of work.

Answer:

A concurrency strategy is a mediator that stores data in the cache and retrieves them from the cache. Before enabling a second-level cache, you need to decide for each persistent class & collection which cache concurrency strategy to use:

  • Transactional − This strategy is mostly applicable to read-mostly data wherein it is indispensable to prevent stale data in concurrent transactions & the rare case of an update.
  • Read-write – It is used for read-mostly data wherein it is important to prevent stale data in the rare cases of update & concurrent transactions.
  • Nonstrict-read-write- This strategy does not guarantee any consistency between the database & the cache. You can use this strategy if data hardly changes or there is a small likelihood of stale data.
  • Read-only- It is a concurrency strategy best suited for data that never changes. You can use it for reference data only.

Answer:

Java Database Connectivity or JDBC is a standard Java API for database-independent connectivity between Java & a vast range of databases. The JDBC library contains APIs for each task mentioned below commonly associated with database usage:

  • To build a connection to the database.
  • To create & execute MySQL or SQL statements.
  • To modify & view the resulting records.

Answer:

The Configuration object signifies the first Hibernate object one creates in the Hibernate application. It is often created only one time during the application initialization. It represents the configuration or properties file needed by Hibernate.

Answer:

A transaction denotes a unit of work with the database. Mostly, RDBMS supports the transaction functionality. It is handled by the underlying transaction manager & transaction from JTA or JDBC.

Answer:

Query objects use HQL & SQL strings to retrieve data from a database & create objects. An instance of a Query binds the query parameters, restricts the no. of results returned by the query & executes the query finally.

Answer:

  1. Sr.No. Properties & Description
    1 ) hibernate.dialect- It enables Hibernate to generate an appropriate SQL for the chosen database.
    2 ) hibernate.connection.driver_class- The JDBC driver class.
    3 ) hibernate.connection.url- The JDBC URL to the database instance.
    4 ) hibernate.connection.username– This property makes the database username.
    5 ) hibernate.connection.password- It sets the database password.
    6 ) hibernate.connection.pool_size- It limits the no. of connections waiting in the Hibernate database connection pool.
    7 ) hibernate.connection.autocommit- It enables auto-commit mode to be used for JDBC connection.

Answer:

The Hibernate Session interface offers a createCriteria() method that helps create a Criteria object that returns instances of the persistence object’s class when an application executes a criteria query.

Answer:

The first-level cache is a session cache which is also a mandatory cache. All the request needs to pass from the first-level cache. This type of cache is enabled by default, so one cannot disable it. Whenever a query enters an entity for the first time, it gets retrieved from the database & in the first-level cache associated with the Hibernates session.

Answer:

The second-level cache is optional. It is essential to consult the first-level cache before locating an object in the second-level cache. The second-level cache is organized on a per-class or per-collection basis. Its primary responsibility is to cache the objects across sessions.

Answer:

  • Hibernate caching is an application’s performance improvement strategy. It pools the objects into the cache to enable faster execution of queries. Hibernate caching is mainly useful when fetching the same data is executed multiple times. Thus, instead of hitting the database, we can access data from the cache, resulting in reduced throughput time. There are two types of Hibernate Caching:
    First Level Cache:

    • It is enabled by default.
    • The first-level cache belongs to the Hibernate session object.
    • As the first-level cache belongs to the session object, the data stored here isn’t accessible to the entire application since it can use multiple session objects.
  • Second Level Cache:
    • The second-level cache belongs to the SessionFactory object. Here data is accessible to the entire application.
    • The second-level cache is not available by default, so one needs to enable it explicitly.
    • Easy Hibernate or EH Cache, OS Cache, Swarm Cache, and JBoss Cache are examples of second-level cache providers.

Answer:

Below are the main benefits of using the Hibernate:

  • Using Hibernate, we can focus on the business logic as it eliminates the boilerplate code that comes with the JDBC and manages resources.
  • Hibernate has a potent query language, HQL, based on object-oriented concepts. It supports inheritance, association & polymorphism.
  • Hibernate has great support for JPA annotations & XML that make the code implementation independent.
  • Hibernate is an open-source project which has a ton of online documentation available over the internet.
  • It supports lazy initialization & performs database queries only when required.
  • Hibernate is the best for database vendor-specific features through which we can execute native SQL queries.
  • Hibernate cache makes the performance better.

Answer:

A dialect refers to a set of code files or a single file that defines the procedure of connecting the database to the Java class. It plays an important role in understanding the communication with the underlying database. When the original database changes, the dialect & database credentials also need to be changed in the Hibernate configuration.

Answer:

The transient state refers to the initial state of the object. Once you create an instance of the POJO class, the object enters into the transient state. Here, the object is not associated with a Session. Hence, the transient state is not related to any database. So, modifications in the data do not affect any changes in the database. The transient objects exist in the heap memory, which is independent of the Hibernate.

Answer:

Yes, one can declare an entity class as final, but it isn’t considered a good practice as Hibernate deploys proxy patterns for lazy initialization. If you declare it as final, then the Hibernate framework cannot use a proxy pattern or create a subclass; thus, it will limit the performance & improvement options.