Sunday, February 13, 2022

Top 20 Hibernate Interview Questions with Answers for Java Programmers

Hibernate is one of the most popular persistent frameworks in the Java world. Hibernate offers an 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 developers 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 its importance in the Java Web application development field, Hibernate has become one of the most sought-after skills and goes hand in hand with the Spring framework.

That's why Spring and Hibernate interview questions are also very popular in Java interviews, particularly for web development positions. Earlier I have shared some Spring MVC interview questions and due to popular demand, I am now sharing some 20 frequently asked Hibernate questions from various Java interviews.

These questions are very useful for both the 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. Since no list is complete without user involvement if you have seen any good Hibernate questions on your interviews, which are 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.

Btw, I expect that you have some Hibernate experience and knowledge before you go through this list of questions otherwise it would be quite back and forth. If you are a beginner to Hibernate, I suggest you first go through a course like Spring and Hibernate for Beginners which provides all the fundamental knowledge in quick time.

After that you can better understand the points interviewers are looking and these questions will also make sense to you.




20 Hibernate Questions and Answers 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.


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


2. What are the advantages of Hibernate over JDBC? (detailed answer)
Apart from Persistence i.e. saving and loading data from Database, Hibernate also provides the 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.


3. Difference between get() vs load() method in Hibernate? (detailed answer)
This is one of the most frequently asked Hibernate interview questions, I have seen it several times. The key difference between the get() and load() method is that load() will throw an exception if an object with an 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.

Use the load() method, if you know the object exists, and the get() method if you are not sure about the object's existence. See Introduction To Hibernate course on Pluralsight to learn more about how Hibernate works

Hibernate interview questions with answers


Btw, you would need a Pluralsight membership to access this course, which costs around $29 monthly or $299 annually. I have one and I also suggest all developers have that plan because Pluralsight is like NetFlix for Software developers.

It has more than 5000+ good quality courses on all the latest topics. Since we programmers have to learn new things every day, an investment of $299 USD is not bad.

Btw, it also offers a 10-day free trial without any obligation which allows you to watch 200 hours of content. You can watch this course for free by signing for that trial.



4. What is the 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 objects. 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 ends up firing N+1 queries.  It's one of the important Hibernate interview questions and I suggest reading chapter 13 of Java Persistence with Hibernate to understand this problem in more detail.



5. What are some strategies to solve the N+1 SELECT problem in Hibernate? (detailed answer)
This is the follow-up question of the 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, will reduce the N+1 problem to N/K + 1 problem where  K is the size of the batch
2) subselect fetching strategy
3) disabling lazy loading



5. What is the difference between the save() and persist() method in Hibernate? (detailed answer)
The main difference between the save() and persist() method is that, save returns a Serializable object while the return type of the persist() method is void, so it doesn't return anything.

You can further join a comprehensive hibernate course like Master Hibernate and JPA with Spring Boot in 100 Steps to learn Hibernate fundamentals like this. I highly recommend that course. Also, here is a nice diagram that explains the state transition in Hibernate:

Hibernate interview questions for 2 to 3 years experienced Java programmers



7. What is the requirement for a Java object to become a 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 a Hibernate Entity.



8. What are the 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 like first-level cache, second-level cache, and query cache.

The first-level cache is maintained at the Session level and cannot be disabled but the second-level cache is required to be configured with an external cache provider like EhCache.


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


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



11. Does SessionFactory thread-safe in Hibernate? (detailed answer)
SessionFactory is both Immutable and thread-safe and it has just one single instance in the Hibernate application. It is used to create a Session object and it also provides caching by storing SQL queries stored by multiple sessions.

The second-level cache is maintained at the SessionFactory level. This can be a difficult and tricky question for less experienced Java developers who are not familiar with thread-safety and Immutability.


12. What is the difference 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 the former is a single-threaded, short-lived object while the latter is Immutable and shared by all Session.

It also lives until the Hibernate is running. Another difference between Session and SessionFactory is that the former provides first-level cache while SessionFactory provides the Second level cache.


13. What is the 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 don't know about Criterion query or API. You can check out this list of 5 Hibernate and JPA courses for Java Programmers to learn more about JPA and Hibernate.


14. What are other ORM frameworks? Any alternative to 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 the Hibernate framework.


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



16. 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 the Session object. I have left this question unanswered for you to answer or find an answer based on your experience.


17. 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 the Criterion query, Java developers who have not used Hibernate extensively will not know much about features like HQL and Criterion.


18. 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



19. The difference between sorted and ordered collections in Hibernate? (detailed answer)
The main difference between sorted and ordered collection is that sorted collection sorts the data in JVM's heap memory using Java's collection framework sorting methods while the ordered collection is sorted using order by clause in the database itself.

A sorted collection is more suited for a small dataset but for a large dataset, it's better to use an ordered collection to avoid OutOfMemoryError in Java applications.


20. How do you log SQL queries issued by the Hibernate framework in Java applications?
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>


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

Btw, If you are actively preparing for Java interviews then you can also check out Java Programming Interview Exposed book, it not only contains interview questions from Spring and Hibernate but also other important Java topics like core Java, data structure and algorithms, Servlet, JSP, JSF, and design patterns.




22. What is the difference between the transient, persistent, and detached state in Hibernate? (detailed answer)
New objects created in the 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 a Persistent object. While an object which was earlier associated with the Hibernate session but currently it's not associated is known as a detached object.

You can call the save() or persist() method to store those objects into the database and bring them into the Persistent state. Similarly, you can re-attach a detached object to hibernate sessions by calling either the update() or saveOrUpdate() method. See Spring and Hibernate for Beginners to learn more about the persistence object's lifecycle in Hibernate.

Hibernate interview questions with answers




23. 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 you before the second-level cache is used at the SessionFactory level. This is a good question to check if the Candidate has been working in hibernate or not. If he has not worked in Hibernate for a long time then he would get confused in this question.


That's all in this list of Hibernate Interview questions for Java and JEE developers. In this article, we have covered a lot of frequently asked Hibernate questions for both beginners and experienced Java developers from all important topics of the 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 going through the following resources to fill those gaps in your knowledge.


Other Interview Questions articles you may like

Thanks for reading this article, if you like this article and the interview question then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment.

P. S. - If you are just started with Java web development and looking for free courses to learn Spring, Spring MVC, and Spring Boot then you can also check out this list of free Spring Courses from Udemy for Java developers. 

7 comments:

  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
  2. Below question(s) are also useful to judge candidate knowledge:
    How we can integrate hibernate with spring?
    What is @mappedBy annotation?
    what all mapping hibernate supports?
    Write a code persisting Employee object ?

    ReplyDelete
  3. describe isolation levels in database ?
    what is phantom read ?

    ReplyDelete
    Replies
    1. Please add this question too...
      what are the jars used in your project for hibernate.

      Delete
    2. Great questions guys, keep them coming, I'll add them whenever I update the article, how about putting one or two lines about answers as well?

      Delete
  4. nice tutorial for beginner and experience person.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.