Browse by Domains

Top Hibernate Interview Questions and Answers 2024 [Updated]

A Java-based framework, Hibernate framework allows a Hibernate Developer to map plain old Java objects to relational database tables. It helps by simplifying the development of Java application to interact with the database. It is an open source, lightweight, and portable framework. Hibernate framework provides a platform for mapping an object-oriented domain model to a relational database.

The hibernate framework frees developers from data persistence-related complex configurations and tasks by mapping plain old java projects or POJO objects with the database tables in an efficient and abstract manner. Apart from abstraction, queries are also executed efficiently. Thus, saving the development time.

This blog will introduce you to the commonly asked hibernate interview questions that will help you ace your upcoming interviews.

  1. What is Hibernate?
  2. What is the ORM tool?
  3. What are the core interfaces of Hibernate?
  4. Mention some of the advantages of using ORM over JDBC?
  5. Explain Hibernate architecture.
  6. Define criteria in terms of Hibernate.
  7. List some of the database supported by Hibernate.
  8. Mention two components of Hibernate configuration object?
  9. List the key components of Hibernate.
  10. How is SQL query created in Hibernate?

The blog has been divided into two main sections, basic interview questions and intermediate interview questions. Let’s get started.

Table of Contents

  1. Basic Hibernate Interview Questions
  2. Intermediate Hibernate Interview Questions
  3. Hibernate FAQs

Basic Hibernate Interview Questions

1. What is Hibernate?

Hibernate is an object-relational mapping tool that is going to simplify the java application interaction with the Database. It provides the facility to map the java classes to relational database tables and Java data types to SQL data types. which means using hibernate we can simplify the java development effort to talk to the database. It is an open-source persistent framework started by Gavin King in 2001.

2. What is the ORM tool?

ORM stands for object-relational mapping is a programming technique for converting data between a relational database and an object-oriented programming language such as java, c#, etc.

Advantage of ORM tool over JDBC.

  1. It hides the SQL queries from object-oriented logic
  2. The fast development of application
  3. Transaction management and automatic key generation.
  4. No need to deal with the database implementation.

3. What are the core interfaces of Hibernate?

The five core interfaces are used in just about every Hibernate application. using these interfaces you can store and retrieve persistent objects and control transactions.

  1. Session interface: This is the primary interface used by hibernate applications. The instance of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread-safe.
  2. Session Factory interface: This is a factory that delivers the session objects to hibernate applications. Generally, there will be a single SessionFactory for the whole application and it will be shared among the application threads.
  3. Configuration interface: This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate-specific mapping documents.
  4. Transaction interface: This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementation such as a JDBC transaction.
  5. Query and criteria interface: This interface allows the user to perform queries and also control the flow of the query execution.

4. Mention some of the advantages of using ORM over JDBC?

Some of its advantages over JDBC are:

  1. It hides the SQL queries from object-oriented logic
  2. Fast development of application
  3. Transaction management and automatic key generation.
  4. No need to deal with the database implementation.
  5. No need to deal with the SQL Queries to save and retrieve the data.
  6. Easy to learn and use.
  7. Excellent cashing support for the better performance of the application.
  8. Simple configuration

5. Explain Hibernate architecture.

There are many objects in the Hibernate Architecture such as persistent object, session query, session factory, transaction, etc. The applications that are developed with the help of Hibernate can be divided into four parts:

  1. Java Application
  2. Hibernate Framework (Configuration & Mapping)
  3. Internal API (JDBC, JTA, JNDI)
  4. Database (MySQL, PostGreSQL, Oracle)

Let’s talk about the main elements in a Hibernate Architecture.

  1. SessionFactory – Holds a second-level cache of data and provides the factory method to get session objects and clients of ConnectionProvider.
  2. Session – A short-lived object which acts as an interface between database data and the java application objects. It has first-level cache of data and can be used to generate query, transaction, and criteria objects.
  3. Transaction – It is an optional element of the Hibernate Architecture and specifies the atomic unit of work and has methods that are useful for transaction management.
  4. ConnectionProvider – It is an optional element and provides an abstraction to the application from DriverManager.
  5. TransactionFactory – Again an optional element. It is a factory of transaction objects.

6. Define criteria in terms of Hibernate.

The hibernate Session interface provides createCriteria() method, which can be used to create a criteria object that returns instances of the persistence object’s class when your application executes a criteria query.

Example of criteria:

Criteria cr = session.createCriteria(GreatLearning.class);

List results = cr.list();

7. List some of the database supported by Hibernate.

Given below is the list of most popular database management systems –

  1. SolarWinds Database Performance Analyzer
  2. Oracle RDBMS
  3. IBM DB2
  4. Altibase
  5. Microsoft SQL Server
  6. SAP Sybase ASE
  7. Teradata
  8. ADABAS
  9. MySQL
  10. FileMaker
  11. Microsoft Access
  12. Informix
  13. SQLite
  14. PostgresSQL

8. Mention two components of Hibernate configuration object?

It is usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate.

The Configuration object provides two keys components –

DATABASE CONNECTION – This is handled through one or more configuration files supported by Hibernate. These files are hibernate. Properties and hibernate.cfg.xml.

CLASS MAPPING SETUP − This component creates the connection between the Java classes and database tables.

9. List the key components of Hibernate.

  • Session
  • Transaction
  • Query
  • Criteria
  • Configuration
  • SessionFactory

10. How is SQL query created in Hibernate?

The entity manager interface provides a method called create native career avoid this method returns an implementation of equilibria interface which is same as if you call the create query method to create equity the code to a JPA.

Ex.

Call EntityManager.createNativeQuery(String query)method.
Query q=em.createNativeQuery(“SELECT a.firstname,a.lastname”+”FROM Author a”);
Create hibernate.cfg.xml configuration file 
Create Employee.hbm.xml mapping file 
Create Employee.java source file and compile it.
Create ManageEmployee.java source file and compile it.
Execute ManageEmployee binary to run the program.

11. How to enable Hibernate in windows 10?

To enable hibernate in windows 10, click on Windows (symbol)+R, then you see the bottom of the window in that type power options or if u say like Cortana, just say “Hey Cortana launch power options”. Another way to get the power option in the control panel. From the left column, select choose what the power buttons do

Next, if options are greyed out, select change settings that are currently unavailable. Scroll down and check to hibernate box, after that make sure save your settings.

Now, when you open the start menu and select the power button the hibernate option will be available. Then click on Alt+f4 then following the steps above adds the hibernate mode option as well.

12. What is the dialect in hibernate?

For connecting hibernate application with database then we must specify the SQLDialect, which contains the mapping between java language data type and database datatypes. There are many dialect classes for defining the RDBMS.

Hibernate uses dialect configuration to know which database you are using so that, it can switch to the database-specific SQL generator. Hibernate generates all your entity mappings and hibernate queries to Specific database queries and uses JDBC to execute them.

Intermediate Hibernate Interview Questions

13. What is n+1 problem in hibernating?

I want to tell one problem regarding n+1 in hibernate to understand this solution.

Let us assume you have a number of employees in a company and every employee have some number of projects. So, one to many relations between employee and projects. now you have to iterate through the collection of employee and display all the projects name they have so the Query will look like this:

SELECT * FROM employee
SELECT * FROM projects WHERE employeeId=?

Here you have 1 select statement for the employee and if you have n number employees you have to write one more query to select the projects. So at the last, you have to put n+1 select statement in order to perform this operation.

Now the next question is how to solve it?

Using join fetching(it will join the parent and children and fetch all the information in a single statement) we can able to solve the n+1 problem. Our next query will look like this:

FROM employee e JOIN FETCH e.projects p

14. How to enable second-level cache in hibernate?

To enable second-level cache we need to follow some points regarding cache, First level cache enabled by default. Whenever we are loading any object from the database, Then hibernate verify whether that object is available in the local cache memory of that particular session, means first level cache, if not available then hibernate verify whether the object is available in global cache or factory cache second-level cache, if not available then hibernate will hit the database and loads the object from there, and then first stores in the local cache of the session, the first level then in the global cache second-level cache.

Ex:

Session s2=sf.openSession();

s2.beginTransaction();

a=(user)s2.get(user.class,102);

System.out.println(a);

s2.getTransaction().commit();

s2.close();

15. What is cascade in hibernate?

Cascading is about persistent actions involving one object propagating to other objects via an association. Cascading can apply to a variety of Hibernate actions, and it is typically transitive. The cascade attribute of the annotation that defines the association says what actions should cascade for that association.

Cascade = “all” means to apply all primary cascade types.

As of Hibernate 5.3, these types are:

  • delete / remove
  • detach / evict
  • merge
  • lock
  • persist
  • refresh
  • replicate
  • save_update / update

16. What is a session in hibernate?

Session is a lightweight object. The session provides physical connectivity between Java application and database. the Session will be established each time the Java application wants to do something with the database. The session object will be provided by the SessionFactory object. All the persistent objects will be saved and retrieved through the Session object. The session object must be destroyed after using it.

The session is used to create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states:

  1. Transient
  2. Persistent
  3. Detached

17. How to integrate spring with hibernating?

We can integrate spring with Hibernate using Maven.

  1. No need to define hibernate.cfg.xml
  2. we provide all our configurations in the spring config file.

Steps for integration:

  1. Configuration cfg=new configuration();
  2. cfg.configure(“hibernate.cfg.xml);
  3. SessionFactory sf=cfg.buildSessionfactory();
  4. Session s=sf.openSession();
  5. Transaction trn=s.beginTransaction();

Steps to create a simple spring ORM application:

  1. create table 
  2. spring configuration file
  3. model class 
  4. dao class
  5. test class

18. What is the sessionFactory in hibernate?

sessionFactory is an interface, which contains a session instance from a sessionFactory.there is a single sessionFactory for the whole application created during application initialization.

The sessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and maybe reused in a future unit of work.

Syntax:

SessionFactory sf=configuration.buildSessionFactory();

19. How is the HQL query created?

HQL stands for a hibernating query language, HQL is an object-oriented language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties 

HQL queries are translated by Hibernate into conventional SQL queries.

20. Is SessionFactory a thread-safe object?

Yes, SessionFactory is a thread-safe object, many threads can access simultaneously.

21. What is Session?

Session simply means a particular interval of time.

It maintains the connection between the hibernate and database, which is available in the org.hibernate.Session interface which provides methods to insert, update and delete the object.

22. Is Session a thread-safe object?

No, the session is not a thread-safe object, many threads cant access it simultaneously. In other words, you cannot share it between threads.

23. What is the difference between the session.save() and session.persist() method?

The return type of the Session.save() method is java.io.Serializable.It returns the newly generated identifier id value as a serializable object. While return type of the session.persist()method does not return anything. 

Syntax:

Serializable ser=session.save(object);

24. What is the diff between the update and merge methods?

Merge is like combining records from more than one table (while retrieving records from tables based on some conditions). The update is like edit, use to change the value of the record. If you are sure that the session does not contain an already persistent instance with the same identifier, then use the update to save the data in hibernate

If you want to save your modifications at any time without knowing about the state of a session, then use merge() in hibernate.

For Ex:

SessionFactory factory = cfg.buildSessionFactory();  

Session session1 = factory.openSession;

Employee e1 = null;

Object o = session1.get(Employee.class, new Integer(101)); 

s1 = (Employee)o;                                     

session1.close

s1.setMarks(97

Session session2 = factory.openSession();           

Employee s2 = null;                                  

Object o1 = session2.get(Employee.class, new Integer(101)); 

s2 = (Employee)o1;                                   

Transaction tx=session2.beginTransaction();         

session2.merge(s1);  

25. What is automatic dirty checking in hibernate?  

The automatic dirty checking feature of hibernating, calls an update statements automatically on the object that is modified in a transaction.

Let us understand it with the help of an example:

SessionFactory sf=cfg.buildSessionFactory();

Session s=factory.openSession();

Transaction tx=s.beginTransaction();

Employee e=(Employee)s.get(Employee.class,Integer.valueOf(101));

e.setSalary(85000);

tx.commit();

s.close();

Here, after getting employee instance e and we are changing the state of e.

after changing the state, we are committing the transaction. In such a case, the state will be updated automatically. This is known as dirty checking in hibernate.

26. What is diff b/w the first-level cache and second-level cache?

First-level cache:

the first level cache is the session cache. It is a mandatory cache through which all requests must pass. The first-level cache in hibernate is enabled by default. we cannot disable the first level.

The first level cache is associated with the Session object. The session object is created from SessionFactory and it is close lost, once the session is closed.it is retrieved from the database and stored in a first-level cache associated with hibernate session.

Second-level cache:

This is an optional Cache that Hibernate provides. Unlike the first-level cache which is accessible only to the session that maintains it, Second-level Cache is accessible to all Sessions. The Second Level cache is by default disabled. Hibernate also doesn’t provide any caching implementation for that.

27. What is a transaction in hibernate?

A transaction represents a unit of work. If u want the database to do some work for u. then u need to start a transaction and let the database know you are done.

Your transaction will commit when you call session.flush().

28. How to create hibernate projects in eclipse?

The steps to create hibernate projects in eclipse:

  1. First, create the java project in eclipse
  2. Download the hibernate from a website then it shows to your download hibernate library then hit into the hibernate after download, add jar files to hibernate.
  3. Add MySQL JDBC driver to file
  4. Then, Create a Persistent class with mapping information
  5. After creating persistence class then again create  the Hibernate Configuration file
  6. Create a Utility class for initializing the SessionFactory
  7. Create Example code to load the data from Database
  8. After doing all the above points right-click on mouse u see run option then hit on the RUN
  9. Run the Example.

29. How to retrieve data from database using hibernate and spring

To retrieve data from the database, you simply leverage the Hibernate sessions createQuery method, pass in some HQL, convert the guts of the returned Query object into an easy-to-use List, and then loop through the collection of your POJOs contained in the List.

Embark on a learning adventure like no other with our extensive collection of free online courses. Whether you’re interested in diving into the world of Cybersecurity, mastering the art of Management, exploring the wonders of Cloud Computing, or delving into the intricate realm of IT and Software or Artificial Intelligence and Machine Learning, we have courses that cater to your interests and goals.

Hibernate Interview Questions FAQs

What are the disadvantages of hibernate?

Some of the most common disadvantages of hibernate are performance cost, does not allow too many inserts, more complex joins, poor performance in batch processing, learning curve, not good for a small project.

What is SessionFactory in hibernate?

SessionFactory is an interface that can be created by providing an object of configuration, which contains all property details related to DB. It is either pulled from hibernate.cfg.xml file or hibernate.properties file. SessionFactory can be called a factory for session objects.

What is the difference between Session and SessionFactory in hibernate? 

Session objects are one per client; while SessionFactory objects are one per application. SessionFactory helps in creating as well as managing Sessions. Session helps in providing a CRUD interface for mapped classes, and also gets into a more versatile Criteria API.

Is Hibernate good or bad? 

Hibernate is good or bad depending on the kind of hard disk you have. During hibernate, the PC actions are frozen, and the state is safely stored on the hard disk in an enormous hibernation file, which is called hiberfil.sys in Windows systems.

Is hibernate mode safe? 

As compared to sleep, hibernate uses lesser power. If you want to save the battery for a longer time, you can put the PC into hibernation.

What is lazy loading in hibernate?

Lazy Loading is basically a design pattern that is used for deferring initialization of objects, for as long as it is possible. It enhances the performance in hibernate.

Is hibernate bad for SSD? 

Hibernate is not essentially bad for SSD. We can just say, it is not that useful with an SSD. Hibernate enables you to start your work again after putting it to sleep. Hibernate helps in saving everything to disk from memory.

Is it better to hibernate or shut down? 

Putting the PC to hibernate will help in saving the memory state to a hard drive. It also helps in saving power. Shutting down the PC also does not use power, but once you start it again, you have to fully start it up and cannot go back to where you left.

Is it OK to hibernate laptops all the time? 

If you want to keep the PC or laptop off for some days, you can put it on hibernate mode. Even if you have not saved the files, nothing will be affected. However, keeping it always in hibernate mode is not highly advisable.

What is hibernate mode vs. sleep mode?

The hibernate mode saves the information to the hard disk, which will enable your computer to be shut down completely and does not use an energy memory state to a hard drive. Hibernate uses less power. When you put the PC to sleep mode, it stores the documents as well as files that you are operating in RAM and uses lesser power in the entire process.


Avatar photo
Great Learning
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

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

Great Learning Free Online Courses
Scroll to Top