Tuesday, September 12, 2023

Top 10 Hibernate Interview Questions and Answers for 3 to 5 Years Experienced Java Developers

Hibernate Interview Questions are asked on Java J2EE Interviews, mostly for web-based enterprise application development roles. The success and acceptability of Hibernate framework on the Java world have made it one of the most popular Objects Relational Mapping (ORM) solutions in the Java technology stack. Hibernate frees you from database-specific coding and allows you to focus more on utilizing powerful object-oriented design principles to implement core business logic. By using Hibernate you can switch between databases rather easily and also take advantage of out-of-box caching facilities provided by Hibernate, in terms of second-level cache and query cache.

It also frees Java developers from writing JDBC code as Hibernate takes care of that. In short, it provides a complete solution to implement the DAO layer of your Java or JEE application. 

As you know most of Java interview not only contains questions from core Java but also from other Java framework like questions from Spring Framework or Struts interview questions, based upon projects requirements. 

It's good to prepare both Spring and Hibernate questions quite well if you are going to work on a project which uses Hibernate as ORM. Check JD or Job description, and if you see word Hibernate anywhere, get ready to face some Hibernate questions.

And, if you are serious about improving your Hibernate and JPA skills then I also recommend you check out Master Hibernate and JPA with Spring Boot in 100 Steps course by Ranga Rao Karnam on Udemy. It's a great course to learn Hibernate and JPA with Spring Boot in a hands-on and practical manner. It's also very affordable and you can buy it for just $10 on Udemy flash sales.





10 Hibernate Framework and JPA Interview Questions

Here is my list of Hibernate interview questions, which I have collected from friends and colleagues. Hibernate is a popular Object Relational Mapping framework and good knowledge of advantages offered by Hibernate along with Hibernate Session API is key to doing well in any Hibernate interview. 

If you are running short of time for your next interview and don't have enough time to prepare in-depth, I suggest having a look at Java Programming Interview Exposed, one of the better books for preparing Java JEE interviews. It also covers Spring, Hibernate, and other important topics from the interview point of view. 



1. What is the difference between get() and load() in Hibernate?
get vs load is one of the most frequently asked Hibernate Interview questions since the correct understanding of both get() and load() is required to effectively use Hibernate. The main difference between get and load is that get will hit the database if the object is not found in the cache and return a completely initialized object.

This may involve several database calls while the load() method can return proxy if the object is not found in the cache and only hit database if any method other than getId() is called. This can save a lot of performance in some cases. You can also see a difference between get and load in Hibernate for more differences and detailed discussion on this question.

Hibernate interview questions with answers




2. What is the difference between save, persist, and saveOrUpdate methods in Hibernate?
After get vs load, this is another Hibernate Interview question that appears quite often. All three methods i.e. save(), saveOrUpdate() and persist() is used to save objects into database, but has subtle differences e.g. save() can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records. 

Also, the return type of save() is a Serializable object, while the return type of persist() method is void. You can also check save vs persist vs saveOrUpdate for complete differences between them in hibernate.


3. What is named SQL query in Hibernate? 
This Hibernate Interview question is related to query functionality provided by Hibernate. Named queries are SQL queries which are defined in mapping document using <sql-query> tag and called using Session.getNamedQuery() method. 

Named query allows you to refer to a particular query by the name you provided, by the way, you can define named query in hibernate either by using annotations or XML mapping file, as I said above. @NameQuery is used to define a single named query and @NameQueries is used to define multiple named queries in hibernate. You can also see Java Persistence with Hibernate book for more details.


4. What is SessionFactory in Hibernate? is SessionFactory thread-safe?
Another common Interview question related to the Hibernate framework. SessionFactory, as the name suggests, is a factory to hibernate Session objects. SessionFactory is often built during start-up and used by application code to get the session object. It acts as a single data store and it's also thread-safe so that multiple threads can use the same SessionFactory

Usually, a Java JEE application has just one SessionFactory, and individual threads, which are servicing client’s requests obtain hibernate Session instances from this factory, that’s why any implementation of SessionFactory interface must be thread-safe.

Also, the internal state of SessionFactory, which contains all metadata about Object/Relational mapping is Immutable and can not be changed once created.


5. What is Session in Hibernate? Can we share a single Session among multiple threads in Hibernate?
This is usually asked as a follow-up question of the previous Hibernate Interview question. After SessionFactory it's time for the Session. In Hibernate, Session represents a small unit of work in Hibernate, they maintain a connection with the database and they are not thread-safe, which means you can not share Hibernate Session between multiple threads. Though Session obtains database connection lazily it's good to close the session as soon as you are done with it.


6. What is the difference between sorted and ordered collection in hibernate?
This is one of the easy Hibernate interview questions you have ever faced. A sorted collection is sorted in memory by using Java Comparator while an ordered collection uses the database's order by clause for ordering. For large data set it's better to use ordered collection to avoid any OutOfMemoryError in Java, by trying to sort them in memory.


7. What is the difference between a transient, persistent, and detached object in Hibernate?
In Hibernate, Objects can remain in three states transient, persistent, or detached.  An object which is associated with the Hibernate session is called a persistent object. 

Any change in this object will reflect in the database based on your flush strategy i.e. automatic flush whenever any property of object changes or explicit flushing by calling Session.flush() method. 

On the other hand, if an object which is earlier associated with Session, but currently not associated with it is called a detached object. 


Hibernate Interview Questions and Answers


You can reattach detached objects to any other session by calling either the update() or saveOrUpdate() method on that session. Transient objects have newly created an instance of persistence class, which is never associated with any Hibernate Session. 

Similarly, you can call persist() or save() methods to make a transient object persistent. Just remember, here transient doesn’t represent the transient keyword in Java, which is an altogether different thing.


8. What does Session lock() method do in Hibernate?
This one is one of the tricky Hibernate Interview questions because Session's lock() method reattachs objects without synchronizing or updating with the database. So you need to be very careful while using the lock() method. By the way, you can always use the Session's update() method to sync with the database during attachment. 

Sometimes this Hibernate question is also asked as what is the difference between Session's lock() and update() method. You can use this key point to answer that question as well. See Java Persistence with Hibernate for more details.

Hibernate Interview Questions for Java JEE Programmers



9. What is Second-level Cache in Hibernate?
This is one of the first interview questions related to caching in Hibernate, you can expect a few more. Second-level Cache is maintained at SessionFactory level and can improve performance by saving a few database round trips. Another worth noting point is that second-level cache is available to the whole application rather than any particular session.


10. What is the query cache in Hibernate?
This question is Sometimes asked as a follow-up to the last Hibernate Interview question, QueryCache actually stores the result of the SQL query for future calls. Query cache can be used along with second-level cache for improved performance. Hibernate support various open-source caching solution to implement Query cache e.g. EhCache.


11. Why it's important to provide a no-argument constructor in Hibernate Entities? 
Every Hibernate Entity class must contain a no-argument constructor, because Hibernate framework creates an instance of them using Reflection API, by calling Class.newInstance() method. This method will throw InstantiationException if it doesn't find any argument constructor inside the Entity class.


12. Can we make a Hibernate Entity Class final? 
Yes, you can make a Hibernate Entity class final, but that's not a good practice. Since Hibernate uses a proxy pattern for performance improvement in the case of the lazy association, by making an entity final, Hibernate will no longer be able to use a proxy, because Java doesn't allow extension of the final class, thus limiting your performance improvement options.

However, you can avoid this penalty if your persistent class is an implementation of an interface, which declares all public methods defined in the Entity class.


That's all on this list of Hibernate Interview questions and answer for Java developers. No one can doubt the popularity of Hibernate as an ORM solution and if you are going for a Java J2EE position, you can expect questions from Hibernate. Especially Spring and Hibernate are the two most popular Java frameworks in JEE space. Don't forget to share any other Hibernate Interview Questions, which you have been asked and good enough to share with the Java community.


Other Hibernate Articles and Interview Questions you may like
  • Difference between First and Second level cache in Hibernate? (answer)
  • 25 Spring Security Interview Questions with answers (spring security questions)
  • 15 Spring Data JPA questions with answers (spring data jpa questions)
  • Difference between get() and load() method in Hibernate? (answer)
  • 15 Microservices Interview questions with answers (microservice questions)
  • 5 Spring and Hibernate Training Courses for Java developers (list)
  • 17 Spring AOP Interview Questions with Answers (spring AOP questions)
  • 2 Books to Learn Hibernate for Beginners (books)
  • 15 Spring Boot Interview Questions with Answers (spring boot questions)
  • 5 Books to Learn Spring Framework for Beginners (books)
  • 20 Spring MVC and REST Interview Questions with answers (spring mvc questions)
  • Why Hibernate Entity class should not be final in Java? (answer)
  • 10 Hibernate Questions from Java Interviews (list)
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. - And, if you are serious about improving your Hibernate and JPA skills then I also recommend you check out Master Hibernate and JPA with Spring Boot in 100 Steps course by Ranga Rao Karnam on Udemy. It's a great course to learn Hibernate and JPA with Spring Boot in a hands-on and practical manner. It's also very affordable and you can buy it for just $10 on Udemy flash sales. 

19 comments :

inj rav said...

I believe we need to include What is lazy initialization exception.. Which was asked thrice to me in interview.

inj rav said...

one more: what is N+1 problem and strategies to avoid this

Javin @ abstract class interface interview questions said...

@inj rav, Those are really good question, I have also seen lazy initialization exception couple of times, will definitely include those.

Javin @ producer consumer solution BlockingQueue said...

@Surajtamang, Apart from re-attaching a transient object to session, Session.lock(Object object,LockMode lockMode) is also used to perform version check, they do this by acquiring an appropriate LockLevel e.g. LockLevel.READ for version check. Different lock modes are provided to prevent entity from being read and modified simultaneously from multiple source. By the way both overloaded version of lock()method is deprecated and it's advised to use buildLockRequest(LockMode).lock(object) method for similar purpose.

Anonymous said...

Hello, Can you please upload PDF version or let me know if there is any way to download these Hibernate interview Questions as PDF? Thanks

Anonymous said...

In Hibernate how can we change the database only by just changing the hibernate.cfg.xml,if so how can we handle migration issues.

Anonymous said...

It's JavaEE and for such a job interview I would assume questions about JPA and not the proprietary Hibernate API

Anonymous said...

Save, saveorupdate, persist for me the only correct answer is: broken by design

Anonymous said...

Seriously - if presented with these questions and a huge domain model, using Hibernate as persistence, think twice before applying for the job ...

Anonymous said...

What is difference b/w session.getCurrentSession() and session.openSession()?? please answer it in brief.

karup said...

when we use criterian in hibernate ?

Anonymous said...

what about hibernate Polymorphism?

Anonymous said...

Difference b/w sessionFactory.getCurrentSession() and sessionFactory.openSession():
openSession() creates a new normal Session, that needs to be explicitly closed once the required operations are complete.

getCurrentSession() - introduced in Hibernate 3.0 - returns a Contextual Session, which is nothing but one Session per Transaction. The Session is automatically closed once the transaction is committed. Also, it enforces the developer to make sure he uses only one session one transaction policy that hibernate recommends. Make sure that you invoke this method from within a Transactional Context, else it may throw an Exception.

Anonymous said...

What design pattern does session factory uses? Answer is singleton. One object per application per database connection.

Anonymous said...

Hi Javin,
I found this Q&A "What does Session lock() method do in Hibernate?" not so clear. Can you please explain on this matter little more?

Here U Go said...

There is another question difference between update and merge.
Ans: Use update() if you are certain that the session does not contain an already persistent instance with the same identifier. Use merge() if you want to merge your modifications at any time without consideration of the state of the session.

How object state changes from persistent to transient?
Ans: delete() method,
Please correct if its wrong, elaborate if anyone can.

Anonymous said...

You can also see this list of Hibernate interview questions which is latest and up to date until 2016. You will most likely be asked about N+1 problem in Hibernate.

kavi...raj said...

Hi All,please clear my confusion,
If object is thread-safe it means multiple thread can access the object or not?
As i know thread-safe means only one thread can access the object at a time.

Unknown said...

J2EE name has been changed new name is JakartaEE.

Post a Comment