Top 20 Hibernate Interview Questions for Java J2EE Programmers

Hibernate is one of the most popular persistent frameworks in Java world. Hibernate offers object to relational (ORM) solution which frees Java developers from writing tedious, hard to read and cluttered JDBC code converting SQL columns into Object properties. Apart from freeing Java developer from writing JDBC and database interaction code, Hibernate also offers the out-of-box solution on caching, proxying and lazy loading which drastically improves the performance of your Java Web application. Given it's important in Java Web application development field Hibernate has become of one of the  most sought after skill and goes hand in hand with Spring framework. That's why Hibernate interview questions are also very popular in Java interviews. Earlier I have shared some Spring MVC interview questions and due to popular demand, I am now sharing 20 odd Hibernate questions from various Java interviews.

These questions are very useful for both phone and the face-to-face round of interviews and both beginners and experienced Java developers up to 2 to 5 years can benefit from these questions. If you are actively preparing for Java interviews than you can also check out Java Programming Interview Exposed, it not only contains interview questions from Spring and Hibernate but also other important Java topics e.g. core Java, data structure and algorithms, Servlet, JSP, JSF and design patterns.


Since no list is complete without user involvement, so if you have seen any good Hibernate questions on your interviews, which is not on this list then feel free to share with us. You can also share your own questions for which you are looking answers or you feel it's a good question to be asked on Java JEE programming interviews.




20 Hibernate Questions from Java JEE Interviews

Here is my selected list of 20 Hibernate based questions for Java developers. It contains questions from Hibernate fundamentals, one-to-one, and one-to-many mappings, caching, Hibernate vs JDBC comparison, pros and cons of Hibernate, known problems with Hibernate, and Performance improvement.


What is Hibernate?
Hibernate is an ORM (Object-relational Mapping) framework, which allows the developer to concentrate on business logic by taking care of persistence of data by itself. Java developer can write code using object and Hibernate can take care of creating those object from data loaded from the database and saving update back to the database.


What are the advantages of Hibernate over JDBC? (detailed answer)
Apart from Persistence i.e. saving and loading data from Database, Hibernate also provides following benefits
1) Caching
2) Lazy Loading
3) Relationship management and provides code for mapping an object to the data
4) The developer is free from writing code to load/store data into the database.


Difference between get() vs load() method in Hibernate? (detailed answer)
This is one of the most frequently asked Hibernate interview question, I have seen it several times. The key difference between get() and load() method is that load() will throw an exception if an object with id passed to them is not found, but get() will return null. Another important difference is that load can return proxy without hitting the database unless required (when you access any attribute other than id) but get() always go to the database, so sometimes using load() can be faster than the get() method. It makes sense to use the load() method if you know the object exists but get() method if you are not sure about object's existence.

Hibernate interview questions with answers




What is N+1 SELECT problem in Hibernate? (detailed answer)
The N+1 SELECT problem is a result of lazy loading and load on demand fetching strategy. In this case, Hibernate ends up executing N+1 SQL queries to populate a collection of N elements. For example, if you have a List of N Items where each Item has a dependency on a collection of Bid object. Now if you want to find the highest bid for each item then Hibernate will fire 1 query to load all items and N subsequent queries to load Bid for each item. So in order to find the highest bid for each item your application end up firing N+1 queries.  It's one of the important Hibernate interview questions and I suggest to read chapter 13 of Java Persistence with Hibernate to understand this problem in more details.


What are some strategies to solve the N+1 SELECT problem in Hibernate? (detailed answer)
This is the follow-up question of previous Hibernate interview question. If you answer the last query correctly then you would be most likely asked this one. Here are some strategies to solve the N+1 problem:
1) pre-fetching in batches, this will reduce N+1 problem to N/K + 1 problem where  K is size of batch
2) subselect fetching strategy
3) disabling lazy loading


What is the difference between save() and persist() method in Hibernate? (detailed answer)
Main difference between save() and persist() method is that, save returns a Serializable object while return type of persist() method is void, so it doesn't return anything. Here is a nice diagram which explains the state transition in Hibernate:

Hibernate interview questions for 2 to 3 years experienced Java programmers



What is the requirement for a Java object to become Hibernate entity object? (detailed answer)
It should not be final and must provide a default, no-argument constructor. See the detailed answer to learn more about the special requirement for a Java object to become Hibernate Entity.


What are different types of caches available in Hibernate? (detailed answer)
This is another common Hibernate interview question. Hibernate provides the out-of-box caching solution but there are many caches e.g. first level cache, second level cache and query cache. First level cache is maintained at Session level and cannot be disabled but the second level cache is required to be configured with external cache provider like EhCache.


What is the difference between first and second level cache in Hibernate? (detailed answer)
This is again follow-up of previous Hibernate interview question. The first level cache is maintained at Session level while the second level cache is maintained at SessionFactory level and shared by all sessions. You can read these books to learn more about caching in Hibernate.


Does Hibernate Session interface is thread-safe in Java? (detailed answer)
No, Session object is not thread-safe in Hibernate and intended to be used with-in single thread in the application.


Does SessionFactory is thread-safe in Hibernate? (detailed answer)
SessionFactory is both Immutable and thread-safe and it has just one single instance in Hibernate application. It is used to create Session object and it also provide caching by storing SQL queries stored by multiple session. The second level cache is maintained at SessionFactory level. This can be a difficult and tricky question for less experienced Java developers who are not familiar with thread-safety and Immutability.


What is different between Session and Sessionfactory in Hibernate? (detailed answer)
This is another popular Hibernate interview question, mostly at a telephonic round of interviews. The main difference between Session and SessionFactory is that former is a single-threaded, short-lived object while later is Immutable and shared by all Session. It also lives until the Hibernate is running. Another difference between Session and SessionFactory is that former provides first level cache while SessionFactory provides the Second level cache.


What is criterion query in hibernate? (detailed answer)
Criteria is a simplified API for retrieving entities by composing Criterion objects also known as Criterion query. This is a very convenient approach for functionality like "search" screens where you can filter data on multiple conditions as shown in the following example:

List books = session.createCriteria(Book.class)
.add(Restrictions.like("name", "java%") )
.add(Restrictions.like("published_year", "2015"))
.addOrder(Order.asc("name") )
.list();
This can be a tough question if you are not using Hibernate on a daily basis, I have interviewed several Java developers who have used Hibernate but doesn't know about Criterion query or API.


What are other ORM frameworks? Any alternative of Hibernate?
This is a general question, sometimes asked to start the conversation and other times to finish the interview. EJB and TopLink from Oracle are two of the most popular alternative to Hibernate framework.


What is the difference between save() and saveOrUpdate() method of Hibernate? (detailed answer)
Though both save() and saveOrUpdate() method is used to store object into Database, the key difference between them is that save can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records.


What is difference between getCurrentSession() and openSession() in Hibernate? (detailed answer)
An interesting Hibernate interview question as you might have used both getCurrentSession() and openSession() to obtain an instance of Session object. I have left this question unanswered for you to answer or find an answer based on your experience.


What is Hibernate Query Language (HQL)? (detailed answer)
Hibernate query language, HQL is an object-oriented extension to SQL. It allows you to query, store, update, and retrieve objects from a database without using SQL. This question is also similar to the earlier question about Criterion query, Java developers who have not used Hibernate extensively will not know much about features like HQL and Criterion.


When do you use merge() and update() in Hibernate? (detailed answer)
This is one of the tricky Hibernate interview questions. You should use update() if you are sure that the Hibernate session does not contain an already persistent instance with the same id and use merge() if you want to merge your modifications at any time without considering the state of the session. See Java Persistence with Hibernate for more details.

Hibernate interview questions for 3 to 6 years experienced developers



The difference between sorted and ordered collection in Hibernate? (detailed answer)
The main difference between sorted and ordered collection is that sorted collection sort the data in JVM's heap memory using Java's collection framework sorting methods while ordered collection is sorted using order by clause in the database itself. A sorted collection is more suited for small dataset but for a large dataset, it's better to use ordered collection to avoid OutOfMemoryError in Java application.


How do you log SQL queries issued by the Hibernate framework in Java application?
You can use the show_sql property to log SQL queries issued by the Hibernate framework, Just add the following line in your Hibernate configuration file:

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


What are the three states of a Hibernate Persistence object can be? (detailed answer)
The Hibernate persistent or entity object can live in following three states:
1) transient
2) persistent
3) detached


What is the difference between the transient, persistent and detached state in Hibernate? (detailed answer)
New objects created in Java program but not associated with any hibernate Session are said to be in the transient state. On the other hand, an object which is associated with a Hibernate session is called Persistent object. While an object which was earlier associated with Hibernate session but currently it's not associate is known as a detached object. You can call save() or persist() method to store those object into the database and bring them into the Persistent state. Similarly, you can re-attach a detached object to hibernate sessions by calling either update() or saveOrUpdate() method.


Which cache is used by Session Object in Hibernate? First level or second level cache? (detailed answer)
A Session object uses the first-level cache. As I told before the second level cache is used at SessionFactory level. This is a good question to check if Candidate has been working in hibernate or not. If he has not worked in Hibernate from a long time then he would get confused in this question.


That's all in this list of Hibernate Interview question for Java  and JEE developers. In this article, we have covered a lot of frequently asked Hibernate question for both beginners and experienced Java developers from all important topics of Hibernate framework e.g. Hibernate fundamentals, caching, collection mapping, performance tuning, common issues and Hibernate vs JDBC.  If you find that you lack knowledge in any particular area, I suggest you read Java Persistence with Hibernate one more time to fill the gaps in your knowledge.



1 comment:

  1. Thank you for sharing these questions. I was looking for latest Hibernate interview questions from long time. You can also include some practical questions like

    which version of Hibernate you have used? e.g. Hibernate 3.0?
    Do you use Annotation or config file for Mapping DB columns to object properties?
    Have you used 2nd level cache in Hibernate? Which provider have you used?
    What is benefit of Query caching?

    I know you already have some of them included, but these are the way the were generally asked.

    ReplyDelete