50+ Hibernate Interview Questions and Answers To Boost Your Java Skills

11 min read

Hibernate is a popular ORM tool that is used in enterprise applications for database-related operations and other Java applications. Therefore, top companies are looking for hibernate experts for their day-to-day operations. So, I have decided to write an article on the hibernate interview questions and answers which is mandatory to polish your knowledge before the interview.

Hibernate has significant importance in the Java world because it frees Java developers from writing complex JDBC code converting SQL columns into object properties. It also offers out-of-box solutions on proxying, caching, and lazy loading which improves the overall performance of Java web applications. So, the spring and hibernate interview questions are mostly asked in Java interviews for web development positions.  

Table of Contents

Hibernate Interview Questions

General and Architecture Questions

  • What is Hibernate?
  • What is ORM?
  • What is the Java Persistence API (JPA)?
  • What is the difference between Hibernate and JPA?
  • Explain Hibernate architecture
  • What is HQL in Hibernate?
  • How is the HQL query created?
  • What’s the general hibernate flow using RDBMS?
  • What is the Hibernate validator framework?
  • What are the main benefits of using the Hibernate Framework?
  • What are the key advantages of Hibernate over JDBC?
  • What design patterns are implemented in Hibernate?
  • List some of the popular databases supported by Hibernate
  • What are the best practices could you recommend when you’re using Hibernate?

Configuration and Statistics

  • What are ways to configure Hibernate?
  • What is the purpose of dialect in the configuration?
  • How to integrate Hibernate with a Spring Framework?
  • What is the Hibernate mapping file?
  • How is SQL query created in Hibernate?
  • How to get Hibernate statistics?
  • Enlist two components of the Hibernate configuration object.

Object Mapping

  • How to map an entity to multiple tables?
  • What are the requirements for Entity class?
  • What are the collection types in hibernation?
  • What is a Bag collection?
  • What is the difference between a sorted collection and an ordered collection?

Core Interfaces

  • What are the core interfaces of Hibernate?
  • What is a Hibernate Session?
  • Is the session thread-safe?
  • What is the difference between openSession() and getCurrentSession()?
  • What is SessionFactory?
  • Is SessionFactory thread-safe?

Data Manipulation

  • What is eager loading in Hibernate?
  • What is lazy loading in Hibernate?
  • What is a lazy initialization?
  • What is cascading in hibernate?
  • What is the key difference between merge() and update() methods?
  • What is the main difference between methods save() and persist()?
  • What is the N+1 problem?
  • What is a Named Query?
  • What are the benefits of Hibernate Criteria API?

Transaction Management

  • What is a transaction?
  • What is transaction propagation?
  • Enlist the hibernate isolation levels.
  • What is the difference between an optimistic lock and a pessimistic lock?

Cache Management

  • How many cache levels do you know in Hibernate?
  • What is the 1st level cache?
  • Is it possible to disable 1st level cache?
  • What is the 2nd level cache?
  • What is the difference between 1st and 2nd levels of cache?
  • How to clear the cache?

Hibernate Interview Questions

1. What is Hibernate?

Hibernate is written in Java and it is based on JVM (Java Virtual Machine). It is an open-source software that is used for mapping Java classes to data tables and Java data types to SQL data types. Hibernate makes it easier to create objects independent of database software and provides a reference implementation of Java persistence API that is used for CRUD operations.

2. What is ORM?

Object Relational Mapping (ORM) is a programming technique that is used to convert data between relational databases and OOP (Object Oriented Programming) languages such as C#, Java, etc.

3. What is the Java Persistence API (JPA)?

Java Persistence API (also known as JPA) has the specification for managing the relational data in several applications. JPA’s current version 2.1 was started in July 2011 but approved as final on 22 May 2013. It also helps us in writing implementation-independent code.

4. What is the major difference between Hibernate & JPA?

Hibernate is an ORM tool that is used to save the state of any Java object into the database whereas JPA defines the management of relational data in the Java applications.

5. Explain Hibernate Architecture

Hibernate architecture is based on many objects including session factory, persistent object, connection factory, transaction, session, transaction factory, etc. It is categorized into the following layers:

  • Java application layer
  • Hibernate framework layer
  • Backhand API layer
  • Database layer

As you can view in the diagram given below:

Explain Hibernate Architecture

6. What is HQL in Hibernate?

Hibernate Query Language (HQL) is an object-oriented language that is independent of the database and considers the Java objects in a similar way as that of SQL.

7. How is the HQL query created?

The HQL query is created with the following syntax:

Session.createQuery

8. What’s the general hibernate flow using RDBMS?

The flow of hibernate communication with RDBMS is:

  • The hibernate flow using RDBMS starts with loading the Hibernate configuration file and creation of the configuration object (It will automatically load all hbm mapping files)
  • The session factory will be created from the configuration object
  • Get one session from this session factory
  • Create HQL Query
  • Now run the query to get the list having Java objects

9. What is the Hibernate validator framework?

The hibernate validator framework allows to expression and validation of different constraints of the application by overriding and extending through XML. Moreover, it is available for both server and client-side programming.

10. What are the main benefits of using the Hibernate Framework?

The following are the main benefits of using the Hibernate Framework:

  • We can focus on our business logic because it eliminates all the boilerplate code that comes with JDBC and takes care of managing resources.
  • It has powerful query language (HQL) which is based on object-oriented concepts and supports inheritance, polymorphism, and association.
  • Hibernate has great support for XML and JPA annotations that make our code implementation independent.
  • It is an open-source project and tons of online documentation are available over the internet.
  • Hibernate supports lazy initialization and performs the database queries only when it is required.
  • For database vendor-specific features, hibernate is best because we can execute native SQL queries.
  • Hibernate cache helps to get better performance

11. What are the key advantages of Hibernate over JDBC?

The following are the key advantages of the hibernate framework over JDBC:

  • Hibernate makes the code cleaner and more readable by removing boilerplate code.
  • Unlike JDBC API, Hibernate supports inheritance, associations, and collections.
  • Hibernate provides transaction management while in JDBC API we need to write code for transaction management using commit and rollback.
  • HQL is more object-oriented and very close to Java programming language. For JDBC, it is mandatory to write native SQL queries.
  • JDBC has poor performance because it doesn’t support caching but Hibernate has great caching options to provide the best performance.
  • Hibernate supports JPA annotations whereas JDBC code is tightly coupled with the application.

12. What design patterns are implemented in Hibernate?

The following design patterns are used in the Hibernate framework:

  • Domain Model Pattern is an object model of the domain that incorporates both behavior and data
  • Data Access Object (DAO) Design Pattern
  • Abstract Factory
  • Data Mapper
  • Query Object for Criterion API
  • Façade
  • Proxy for lazy loading
  • Object-Relational Mapping (ORM)

13. List some of the popular databases supported by Hibernate

Following are the hibernate-supported databases:

  • DB2
  • MySQL
  • Oracle
  • HSQL
  • FrontBase
  • PostgreSQL
  • Sybase SQL Server
  • Informix Dynamic Server

14. What are the best practices could you recommend when you’re using Hibernate?

Following best practices are recommended when we use the hibernate:

  • Persistent classes should Implement hashCode() and equals()
  • Avoid references to the ID in the persistent class’ method equals()
  • Avoid public/protected setter for the generated identifier field
  • Avoid many-to-many association
  • Never use an array to map a collection
  • equals() and hashCode() must access the fields through getter methods
  • Avoid non-serializable Entities

Configuration and Statistics

15. What are ways to configure Hibernate?

Hibernate can be configured in the following ways:

  • Using APIs (programmatically): In a programmatical way, the APIs are used to load the hbm file along with the database driver providing connection details.
  • Using XML File: By specifying the database connection details in an XML configuration file named hibernate.cfg.xml that’s loaded along with the hbm file.
  • Using Properties File: By using a .properties file named hibernate.properties.

16. What is the purpose of dialect in the configuration?

In the configuration, the dialect knows which database you are using so that it can be switched to the database-specific SQL generator code whenever you need it.

17. How to integrate Hibernate with a Spring Framework?

Hibernate is one of the popular ORM frameworks and Spring is a widely used Java EE framework. So, the spring hibernate combination is used in a lot of enterprise-level applications. Following are the simple steps for hibernate and spring integration:

  • Create a table in the database (optional step)
  • Create an applicationContext.xml file that contains DataSource and SessionFactory etc.
  • Create Employee.java file (persistent class)
  • Create employee.hbm.xml file (mapping file)
  • Create EmployeeDao.java file that uses HibernateTemplate
  • Create InsertTest.java file that calls methods of the EmployeeDao class

18. What is a Hibernate mapping file?

The mapping file is one of the key features of hibernation because it is a compulsory feature for every ORM tool. It is a mechanism of placing an object property into columns of a table because it establishes a relationship between two database tables as an attribute in their model and allows you to easily navigate the criteria queries and associations in your model. 

19. How is SQL query created in Hibernate?

The SQL query is created using the following syntax:

Session.createSQLQuery

20. How to get Hibernate statistics?

We can get the hibernate statistics by setting the property hibernate.generate_statistics to true. It will show several useful metrics but it is only available in development mode.

21. Enlist two components of the Hibernate configuration object.

Database Connection

Class Mapping Setup

Object Mapping

22. How to map an entity to multiple tables?

Following are the simple steps to map an entity to 2 database tables:

  • Annotate your entity with JPA’s @Table and @SecondaryTable annotations, in addition, provide the names of the first and second tables as the name parameters.
  • Annotate each attribute that you need to map to the secondary table with a @Column annotation and add the secondary table name as the value of the table attribute.

23. What are the requirements for Entity class?

The following are the requirements for an entity class:

  • It essentially annotated with the javax.persistence.Entity annotation
  • The class may have other constructor methods but it must have a public or protected, no-argument constructor
  • The persistent instance variables or no methods must be declared final but the class will never be declared final
  • When the entity instance is passed using its value as a detached object then the class must implement the Serializable interface
  • Entities may extend both entity & non-entity classes, but non-entities only used to extend entity classes
  • Persistent instance variables must be declared using private, protected, or package-private and can be accessed directly by the entity class’s methods through accessor or business methods

24. What are the collection types in hibernation?

  • Bag
  • Set
  • List
  • Array
  • Map

25. What is a Bag collection?

The bag is a Java collection that is used to store the elements without caring about sequencing and allow duplicate elements in the list. In simple words, it is a random grouping of the objects in a list that is mapped with a <bag> element.

26. What is the difference between a sorted collection and an ordered collection?

As the name indicates sorted collection is based on the elements having order but the order depends on the value of the element such as the sorted set.

An ordered collection is the name of elements having a specific order and it is independent of the value such as a list.

Core Interfaces

27. What are the core interfaces of Hibernate?

Following are the core interfaces of the hibernate framework:

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

28. What is a Hibernate Session?

A hibernate session is a runtime interface that is used between the application and hibernates. In simple words, it establishes a connection between the application and the database to perform different functions such as create, delete, get, and update.

29. Is the session thread-safe?

No, it is not a thread-safe object because it can be accessed by multiple threads.

30. What is a difference between openSession() and getCurrentSession()?

SessionFactory.openSession creates a new session object and gives it to you for performing different operations. But keep in mind, you need to close these session objects because these are not thread-safe. If you have a multithreaded environment then you need to create one session per request. Moreover, one session per request is also used in web applications.

SessionFactory.getCurrentSession creates a new session if not exist otherwise it will use the same session. The object provided by the getCurrentSession is managed internally and automatically closes the session when a transaction ends, so there is no need to manage it externally. 

31. What is SessionFactory?

SessionFactory can be created by providing a configuration object and it is an interface that contains all DB-related property details pulled by hibernate.properties or hibernate.cfg.xml. In short, it is a factory for session objects that is created during application start-up and kept for later use because it is a heavyweight object.

32. Is SessionFactory thread-safe?

Yes, many threats cannot access it at the same time.

Data Manipulation

33. What is eager loading in Hibernate?

Eager loading is a design pattern in which the data initialization phase is completed on the spot and it is considered the best option when the relations are not too much. It is the best practice to reduce the further queries on the server.

34. What is lazy loading in Hibernate?

Lazy loading means whenever the select query is executed it will not directly access the database and wait for the function i.e. when we need then it will fetch from the database.

35. What is a lazy initialization?

Lazy initialization or lazy fetching is the opposite of eager and it means when a record is loaded for the database the child rows ( in case of too many relationships) are not loaded.

36. What is cascading in hibernate?

It is about persistent actions involving an object propagating to other objects with the help of association. Cascading can apply to a range of hibernate actions and it is characteristically transitive.

37. What is the key difference between merge() and update() methods?

Merge() is used to synchronize all data changes such as removal and addition of row but update can only modify column values.

38. What is the main difference between save() and persist() methods?

The persist () method is similar to the save method that is also used to INSERT the records in the database but it has a void return type whereas the save has the return type of Serializable Object.

39. What is the N+1 problem?

It is a problem that happens when the data access framework executes N additional SQL statements to fetch the same data that could have been accessed when executing primary SQL statements/queries. The larger the value of N the more queries will be executed and have a great performance impact.

40. What is a Named Query?

The named query is the name of a predefined unchangeable query string which is similar to alias names. It can be defined by a mapping file or annotation.

41. What is the key benefit of Hibernate Criteria API?

The main benefit of hibernate criteria API is that it is dedicatedly designed to manipulate data without any hard-coded SQL statements.

Transaction Management

42. What is a transaction?

A transaction is an event that represents a unit of work that can be described by ACID properties (Atomicity, Consistency, Isolation, and Durability). So, if one step fails, the whole transaction fails which is known as atomicity.

43. What is transaction propagation?

Transaction propagation shows if any component will or will not participate in any particular transaction and how will it behave if the calling service or component already has or does not have a transaction created already.

44. Enlist the hibernate isolation levels.

Following are the Hibernate isolation levels: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE.

45. What is the difference between an optimistic lock and a pessimistic lock?

Before committing the transaction, optimistic locking is used when you check if the record was updated by someone else. In the case of pessimistic locking, you take an exclusive lock so that you can make sure no one else can modify the record.

Cache Management

46. How many cache levels do you know in Hibernate?

Two caching levels exist in the hibernate: first-level cache and second-level cache. In the first level cache, objects are cached within the current session and only alive until a session is closed but the second level cache exists as long as the SessionFactory is alive.

47. What is the 1st level cache?

The first level cache provides the session level in the process caching. Once the session is created, a session cache is associated with it and the copy of a session cache is maintained when an object is loaded in from the database.

48. Is it possible to disable 1st level cache?

No, you cannot disable the 1st level cache.

49. What is the 2nd level cache?

2nd level cache is a store of entity data managed by the persistence provider to improve the performance of the application by avoiding expensive database calls and keeping the entity data local to the application.

50. What is the difference between 1st and 2nd levels of cache?

The main difference is that 1st level cache is maintained at the session level while the 2nd level cache is maintained at SessionFactory. The data stored in the first level cache is only accessible to the session who maintains it while the second level cache is accessible to all.

51. How to clear cache?

You can use the session evict() method to remove a single object from the first-level cache but if you want to delete all the objects from the cache then session clear() is used for this purpose.

That’s all for Hibernate Interview Questions and Answers, I hope it will help both beginners and experienced people. Moreover, take a look at compulsory things including industry research, reasons you want the job, preparation for common interview questions, practice, practice, and practice. Moreover, you can also prepare 100+ SQL Interview Questions and Answers to understand the database concepts.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Make Your Website Live Today

Choose one of your required Web Hosting Plan at market competitive prices

Temok IT Services
© Copyright TEMOK 2024. All Rights Reserved.