Core Java

Impoetant Interview Questions/Answers of Hibernate

Java Interview

Hibernate interview questions contains 20% of weight in an interview, so in this article, I cover most frequently asked hibernate interview questions to crack interview easily. If you want to stand out of thousands of candidates then read this article it will clear your basics java concepts.”


Q1.  What is Hibernate Framework?

Hibernate ORM (Hibernate in short) is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Q2. What is Java Persistence API (JPA)?

The Java Persistence API (JPA) is a Java application programming interface specification that describes the management of relational data in applications using Java Platform, Standard Edition and Java Platform, Enterprise Edition.

Q3.  What are the important benefits of using Hibernate Framework?

Hibernate is database independent. You can work with any database you want like oracle, MySQL, db2, SQL server, etc. Using hibernate you won’t worry about writing database specific queries and syntax. It provides HQL (Hibernate Query Language), which is compatible with any database server. You just need to write queries in HQL, at the end hibernate converts HQL to underlying database and executes it.

In ORM, you will map a database table with java object called “Entity”. So once you map these, you will get advantages of OOP concepts like inheritance, encapsulation, etc.

Caching mechanism (1st level & 2nd level cache) provided hibernate means you don’t need to hit the database for similar queries, you can cache it and use it from buffered memory to improve performance.

Supports Lazy loading (also called n+1 problem in Hibernate). Take an example-parent class has n number of the child class. So When you want information from only 1 child class, there is no meaning of loading n child classes.This is called lazy loading (Load only thing which you want).

Q4. Name some important interfaces of Hibernate framework?

The core interfaces of Hibernate framework are:

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

Q5. What is hibernate configuration file?

Hibernate also requires a set of configuration settings related to database and other related parameters. All such information is usually supplied as a standard Java properties file called hibernate.properties, or as an XML file namedhibernate.cfg.xml.

Q6. What is hibernate mapping file?

The mapping document is an XML document having <hibernatemapping> as the root element which contains all the <class> elements. The <class> elements are used to define specific mappings from a Java classes to the database tables.

Q7. What is Hibernate SessionFactory and how to configure it?

SessionFactory is the factory class used to get the Session objects. SessionFactory is responsible to read the hibernate configuration parameters and connect to the database and provide Session objects. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.

The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.

Q8. What is Hibernate Session and how to get it?

It maintains a connection between hibernate application and database.

Hibernate Session provides methods to store, update, delete or fetch data from the database such as persist(), update(), delete(), load(), get() etc.

It is a factory of Query, Criteria and Transaction i.e. it provides factory methods to return these instances.

Q9. What is the difference between Hibernate Session get() and load() method?

Hibernate session comes with different methods to load data from database. get and load are most used methods, at first look they seems similar but there are some differences between them.

  • get() loads the data as soon as it’s called whereas load() returns a proxy object and loads data only when it’s actually required, so load() is better because it support lazy loading.
  • Since load() throws an exception when data is not found, we should use it only when we know data exists.
  • We should use get() when we want to make sure data exists in the database.

Q10. What is hibernate caching? Explain Hibernate first level cache?

As the name suggests, hibernate caches query data to make our application faster. Hibernate Cache can be very useful in gaining fast application performance if used correctly. The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application.

Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However, hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely.Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.

Q11. What is difference between Hibernate save(), saveOrUpdate() and persist() methods?

Hibernate save can be used to save entity to the database. The problem with save() is that it can be invoked without a transaction and if we have mapping entities, then only the primary object gets saved causing data inconsistencies. Also save returns the generated id immediately.

Hibernate persist is similar to save with transaction. I feel it’s better than save because we can’t use it outside the boundary of the transaction, so all the object mappings are preserved. Also, persist doesn’t return the generated id immediately, so data persistence happens when needed.

Hibernate saveOrUpdate results into insert or update queries based on the provided data. If the data is present in the database, update query is executed. We can use saveOrUpdate() without transaction also, but again you will face the issues with mapped objects not getting saved if the session is not flushed.

Q12. What is the difference between sorted collection and ordered collection, which one is better?

When we use Collection API sorting algorithms to sort a collection, it’s called sorted list. For small collections, it’s not much of an overhead but for larger collections, it can lead to slow performance and OutOfMemory errors. Also, the entity beans should implement Comparable or Comparator interface for it to work, read more at java object list sorting.

If we are using Hibernate framework to load collection data from the database, we can use its Criteria API to use “order by” clause to get ordered list. Below code snippet shows you how to get it.

” List<Employee> empList = session.createCriteria(Employee.class) .addOrder(Order.desc(“id”)).list(); “

Ordered list is better than sorted list because the actual sorting is done at database level, that is fast and doesn’t cause memory issues.

Q13. What are the collection types in Hibernate?

There are five collection types in hibernate used for one-to-many relationship mappings.

  • Bag
  • Array
  • Set
  • List
  • Map

Q14. What is HQL and what are it benefits?

Hibernate Framework comes with a powerful object-oriented query language – Hibernate Query Language (HQL). It’s very similar to SQL except that we use Objects instead of table names, that makes it more close to object oriented programming.

Hibernate query language is case-insensitive except for java class and variable names.

The HQL queries are cached but we should avoid it as much as possible, otherwise, we will have to take care of associations. However, it’s a better choice than native SQL query because of Object-Oriented approach.

Q15. What is Query Cache in Hibernate?

The Hibernate second level cache is an application level cache for storing entity data. The query cache is a separate cache that stores query results only.

Q16. What is Named SQL Query?

Hibernate provides Named Query that we can define at a central location and use them anywhere in the code. We can create named queries for both HQL and Native SQL.

Hibernate Named Queries can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery and @NamedNativeQuery.

Q17. How to log hibernate generated SQL queries in log files?

We can set below property for hibernate configuration to log SQL queries.

<property name=”hibernate.show_sql”>true</property>

However, we should use it only in Development or Testing environment and turn it off in a production environment.

Q18. What is Hibernate Proxy and how it helps in lazy loading?

Hibernate uses a proxy object to support lazy loading. Basically, when you load data from tables, hibernate doesn’t load all the mapped objects. As soon as you reference a child or lookup object via getter methods, if the linked entity is not in the session cache, then the proxy code will go to the database and load the linked object. It uses javassist to effectively and dynamically generate sub-classed implementations of your entity objects.

Q19. How to implement relationships in hibernate?

We can easily implement one-to-one, one-to-many and many-to-many relationships in hibernate. It can be done using JPA annotations as well as XML based configurations. For better understanding, you should go through following tutorials.

  • One to One Mapping
  • One to Many Mapping
  • Many to Many Mapping

Q20. What is cascading and what are different types of cascading?

When we have a relationship between entities, then we need to define how the different operations will affect the other entity. This is done by cascading and there are different types of it.

The cascade types supported by the Java Persistence Architecture are as below:

  • PERSIST: means that save() or persist() operations cascade to related entities.
  • MERGE: means that related entities are merged into managed state when the owning entity is merged.
  • REFRESH: does the same thing for the refresh() operation.
  • REMOVE: removes all related entities association with this setting when the owning entity is deleted.
  • DETACH: detaches all related entities if a “manual detach” occurs.
  • ALL: is shorthand for all of the above cascade operations.

Q21. What is HibernateTemplate class?

HibernateTemplate is a helper class that is used to simplify the data access code. This class supports automatically converts HibernateExceptions which is a checked exception into DataAccessExceptions which is an unchecked exception. HibernateTemplate is typically used to implement data access or business logic services. The central method is execute(), that supports the Hibernate code that implements HibernateCallback interface.

Q22. How to integrate Hibernate with Servlet or Struts2 web applications?

Hibernate integration with Servlet or Struts2 needs to be done using ServletContextListener. 

Q23. Which design patterns are used in Hibernate framework?

Some of the design patterns used in Hibernate Framework are:

  • Domain Model Pattern – An object model of the domain that incorporates both behavior and data.
  • Data Mapper – A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself.
  • Proxy Pattern for lazy loading
  • Factory pattern in SessionFactory

Q24. What is Hibernate Validator Framework?

Data validation is an integral part of any application. You will find data validation at presentation layer with the use of Javascript, then at the server side code before processing it. Also, data validation occurs before persisting it, to make sure it follows the correct format.

Q25. What is the benefit of Hibernate Tools Eclipse plugin?

Hibernate Tools plugin helps us in writing hibernate configuration and mapping files easily. The major benefit is the content assist to help us with properties or XML tags to use. It also validates them against the Hibernate DTD files, so we know any mistakes before hand. Learn how to install and use at Hibernate Tools Eclipse Plugin.