Java Certification Training Course
- 44k Enrolled Learners
- Live Class
Hibernate is one of the most widely used ORM tools for building Java applications. It is used in enterprise applications for database operations. So, this article on hibernate interview questions will help you to brush up your knowledge before the interview.
If you are a fresher or an experienced, this is the right platform for you which will help you to start your preparation for the Hibernate job roles.
Let’s begin by taking a look at the most frequently asked questions in Hibernate Interview Questions.
Q1. What is Hibernate?
Q2. What are the major advantages of Hibernate Framework?
Q3. What are the advantages of using Hibernate over JDBC?
Q4. What is an ORM tool?
Q5. Why use Hibernate Framework?
Q6. What are the different functionalities supported by Hibernate?
Q7. What are the technologies that are supported by Hibernate?
Q8. What is HQL?
Q9. How to achieve mapping in Hibernate?
Q10. Name some of the important interfaces of Hibernate framework?
For better understanding, I have divided the rest of the Hibernate Framework Interview Questions into the following sections:
Hibernate is one of the most popular Java frameworks that simplify the development of Java application to interact with the database. It is an Object-relational mapping (ORM) tool. Hibernate also provides a reference implementation of Java API.
It is referred as a framework which comes with an abstraction layer and also handles the implementations internally. The implementations include tasks like writing a query for CRUD operations or establishing a connection with the databases, etc.
Major advantages of using Hibernate over JDBC are:
It is basically a technique that maps the object that is stored in the database. An ORM tool helps in simplifying data creation, manipulation, and access. It internally uses the Java API to interact with the databases.
Hibernate overcomes the shortcomings of other technologies like JDBC.
Hibernate supports a variety of technologies, like:
Association mappings are one of the key features of Hibernate. It supports the same associations as the relational database model. They are:
You can map each of them as a uni- or bidirectional association.
Hibernate interfaces are:
In this type of mapping, you only need to model the system for the entity for which you want to navigate the relationship in your query or domain model. You need an entity attribute that represents the association, so annotate it with an @OneToOne annotation.
In this type of association, one object can be associated with multiple/different objects. Talking about the mapping, the One-to-Many mapping is implemented using a Set Java collection that does not have any redundant element. This One-to-Many element of the set indicates the relation of one object to multiple objects.
Many-to-Many mapping requires an entity attribute and a @ManyToMany annotation. It can either be unidirectional and bidirectional. In Unidirectional, the attributes model the association and you can use it to navigate it in your domain model or JPQL queries. The annotation tells Hibernate to map a Many-to-Many association. The bidirectional relationship, mapping allows you to navigate the association in both directions.
Spring is also one of the most commonly used Java frameworks in the market today. Spring is a JavaEE Framework and Hibernate is the most popular ORM framework. This is why Spring Hibernate combination is used in a lot of enterprise applications.
Following are the steps you should follow to integrate Spring and Hibernate.
Hibernate Configuration File mainly contains database-specific configurations and are used to initialize SessionFactory. Some important parts of the Hibernate Configuration File are Dialect information, so that hibernate knows the database type and mapping file or class details.
Hibernate supports JPA annotations. Some of the major annotations are:
Hibernate Session is the interface between Java application layer and Hibernate. It is used to get a physical connection with the database. The Session object created is lightweight and designed to be instantiated each time an interaction is needed with the database. This Session provides methods to create, read, update and delete operations for a constant object. To get the Session, you can execute HQL queries, SQL native queries using the Session object.
SessionFactory is the factory class that is used to get the Session objects. The SessionFactory is a heavyweight object so usually, it is created during application startup and kept for later use. This SessionFactory is a thread-safe object which is used by all the threads of an application. If you are using multiple databases then you would have to create multiple SessionFactory objects.
This getCurrentSession() method returns the session bound to the context and for this to work, you need to configure it in Hibernate configuration file. Since this session object belongs to the context of Hibernate, it is okay if you don’t close it. Once the SessionFactory is closed, this session object gets closed.
openSession() method helps in opening a new session. You should close this session object once you are done with all the database operations. And also, you should open a new session for each request in a multi-threaded environment.
The following steps help in configuring Hibernate file:
The configuration provides 2 key components, namely:
Hibernate provides the facility to persist the Collections. A Collection basically can be a List, Set, Map, Collection, Sorted Set, Sorted Map. java.util.List, java.util.Set, java.util.Collection, etc, are some of the real interface types to declared the persistent collection-value fields. Hibernate injects persistent Collections based on the type of interface. The collection instances generally behave like the types of value behavior.
There are five collection types in hibernate used for one-to-many relationship mappings.
When you integrate Spring and Hibernate, Spring ORM provides two helper classes – HibernateDaoSupport and HibernateTemplate. The main reason to use them was to get two things, the Session from Hibernate and Spring Transaction Management. However, from Hibernate 3.0.1, you can use the SessionFactory getCurrentSession() method to get the current session. The major advantage of using this Template class is the exception translation but that can be achieved easily by using @Repository annotation with service classes.
The following are the benefits of using this Hibernate template class:
There are a few design patterns used in Hibernate Framework, namely:
Hibernate incorporates Dirty Checking feature that permits developers and users to avoid time-consuming write actions. This Dirty Checking feature changes or updates fields that need to be changed or updated, while keeping the remaining fields untouched and unchanged.
Q30. What is meant by Light Object Mapping?
The means that the syntax is hidden from the business logic using specific design patterns. This is one of the valuable levels of ORM quality and this Light Object Mapping approach can be successful in case of applications where there are very fewer entities, or for applications having data models that are metadata-driven.
Optimizing the performance of Hibernate applications is known as Hibernate tuning.
The performance tuning strategies for Hibernate are:
Transaction Management is a property which is present in the Spring framework. Now, what role does it play in Hibernate?
Transaction Management is a process of managing a set of commands or statements. In hibernate, Transaction Management is done by transaction interface. It maintains abstraction from the transaction implementation (JTA, JDBC). A transaction is associated with Session and is instantiated by calling session.beginTransaction().
Q33. How do you integrate Hibernate with Struts2 or Servlet web applications?
You can integrate any Struts application with Hibernate. There are no extra efforts required.
Q34. What are the different states of a persistent entity?
It may exist in one of the following 3 states:
Q35. How can the primary key be created by using Hibernate?
A Primary key is a special relational database table column designated to uniquely identify all table records. It is specified in the configuration file hbm.xml. The generator can also be used to specify how a Primary key can be created in the database.
<id name="ClassID" type="string" > <column name= "columnID" length="10" > <generator/> </id>
Q36. Explain about Hibernate Proxy and how it helps in Lazy loading?
Q37. How can we see Hibernate generated SQL on console?
In order to view the SQL on a console, you need to add following in Hibernate configuration file to enable viewing SQL on the console for debugging purposes:
Q38. What is Query Cache in Hibernate?
Hibernate implements a separate cache region for queries resultset that integrates with the Hibernate second-level cache. This is also an optional feature and requires a few more steps in code.
Note: This is only useful for queries that are run frequently with the same parameters.
Q39. What is the benefit of Native SQL query support in Hibernate?
Hibernate provides an option to execute Native SQL queries through the use of the SQLQuery object. For normal scenarios, it is however not the recommended approach because you might lose other benefits like Association and Hibernate first-level caching.
Native SQL Query comes handy when you want to execute database-specific queries that are not supported by Hibernate API such query hints or the Connect keyword in Oracle Database.
Q40. What is Named SQL Query?
Hibernate provides another important feature called Named Query using which you can define at a central location and use them anywhere in the code.
You can create named queries for both HQL as well as for Native SQL. These Named Queries can be defined in Hibernate mapping files with the help of JPA annotations @NamedQuery and @NamedNativeQuery.
Q41. When do you use merge() and update() in Hibernate?
This is one of the tricky Hibernate Interview Questions asked.
update(): If you are sure that the Hibernate Session does not contain an already persistent instance with the same id .
merge(): Helps in merging your modifications at any time without considering the state of the Session.
Q42. Difference between get() vs load() method in Hibernate?
This is one of the most frequently asked Hibernate Interview Questions. The key difference between the get() and load() method is:
load(): It will throw an exception if an object with an ID passed to them is not found.
get(): Will return null.
load(): It can return proxy without hitting the database unless required.
get(): It always goes to the database.
So sometimes using load() can be faster than the get() method.
Q43. Difference between the first and second level cache in Hibernate?
The first-level cache is maintained at Session level while the second level cache is maintained at a SessionFactory level and is shared by all sessions.
Q44. Difference between Session and SessionFactory in Hibernate?
This is yet another popular Hibernate Interview Question asked.
Q45. Difference between save() and saveOrUpdate() method of Hibernate?
Even though 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.
Q46. Difference between sorted and ordered collection in Hibernate?
sorted collection sort the data in JVM’s heap memory using Java’s collection framework sorting methods. The ordered collection is sorted using order by clause in the database itself.
Note: A sorted collection is more suited for small dataset but for a large dataset, it’s better to use ordered collection to avoid
Q47. Difference between the transient, persistent and detached state in Hibernate?
Transient state: New objects are created in the Java program but are not associated with any Hibernate Session.
Persistent state: 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.
Detached state: You can re-attach a detached object to Hibernate sessions by calling either update() or saveOrUpdate() method.
Q48. Difference between managed associations and Hibernate associations?
Managed associations: Relate to container management persistence and are bi-directional.
Hibernate Associations: These associations are unidirectional.
Q49. What are the best practices that Hibernate recommends for persistent classes?
Q50. What are the best practices to follow with Hibernate framework?
I hope this set of Hibernate Interview Questions will help you in preparing for your interviews. All the best!
If you want to learn Hibernate and wish to use it while developing Java applications, we are here to help you guys with it. Also, check out the Java Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.
Got a question for us? Please mention it in the comments section and we will get back to you.