Enterprise Java

Hibernate Interview Questions and Answers – The ULTIMATE List

hibernate interview questions answersThis is a summary of some of the most important questions concerning the Hibernate Framework, that you may be asked to answer in an interview! There is no need to worry for your next interview test, because Java Code Geeks are here for you!

The majority of the things you may be asked is collected in the list below. Our Hibernate interview questions takes you through the complete hibernate framework and provide a thorough understanding of the framework using the questions and answers. The questions are categorized to provide information specific to every module as needed. With these Hibernate interview questions, we ensure that you no longer need to worry about an interview related to Hibernate framework.

The question and answers begin with the introduction of the framework and its concepts. They extend towards the configuration, usage and concepts. To get a little deeper, we cover the questions pertaining to the caching levels and configurations related to the caching. The questions conclude with the explanation of various hibernate specific features that make your programming easier.

Lets get started with the introductory part.

Table of Contents

Hibernate Basics

1. What is an ORM?

Java is an object oriented programming language. In Java, we map almost every real world entity into an object. ORM is an acronym for Object Relational Model. ORM is the basic concept behind the Hibernate framework. ORM is the process of mapping database tables to Java classes or Java objects. Every column in the database is mapped to a different variable in Java. Thus, ORM helps us simplify the process of interacting with database in Java.

2. What is Hibernate framework?

Hibernate framework is a collection of Java classes built to simplify the process of database connection and interaction. Hibernate framework provides an intermediate layer of code between the database and Java code. This layer facilitates the configuration of database, connection pool, query execution as well as caching. Hibernate enables the developer to stay considerably independent of the changes of database.

3. What is a dialect?

A dialect is a set of code files or a single file occasionally that defines the process of connecting database to a Java class. A dialect in Hibernate plays the role of understanding the communication taking place with the underlying database. Whenever the underlying database changes, all you need to change in the Hibernate configuration is the dialect and database credentials. This is true as long as the code uses HQL queries.

4. What are HQL queries?

HQL is an acronym for Hibernate query language. HQL is a simpler way to write queries independent of the database. The HQL queries are understandable by the Hibernate framework. They are converted to normal SQL queries depending on the database dialect that is being used. Normally, without the hibernate framework, the process of changing underlying database involves change of all the queries. With Hibernate framework, if a code is using HQL queries, the process of changing the underlying database is pretty simple. All that is required to be done is change the dialect and DB credentials, the framework takes care of the rest.

5. What are the possible ways to configure Hibernate framework?

The hibernate framework can be configured using XML as well as Java class annotations. However, the Java class based annotation feature was introduced only from Hibernate 4.0. Hence, any lower version supports only XML based configuration.

6. What is a connection pool?

In an enterprise application, the application will be hit by numerous users. If the application server establishes a new connection for every request, it will be a burden on the database server. On the other hand, if there is a single database connection only, there will be a huge overhead of requests for query. Hence, it is preferred to have a limited number of database connections pre-configured in Hibernate. Hibernate framework ensures that new connections are established until the defined maximum limit is reached. Post the limit, Hibernate reuses the database connection object. Thus, Hibernate connection pool is a bunch of Database connection objects created for managing parallel communication with the database.

7. What is JPA?

JPA is an acronym for Java persistence API. This API from Java provides certain predefined annotations in Java which makes database ORM simpler. All you need to do is place these annotations above the class name and variables to map them to the database table.

8. How does JPA help in Hibernate framework?

Before the launch and acceptance of JPA as ORM standards, Hibernate used XML mapping to strict bind the hibernate Value objects to Database objects. This mapping was based on XML and hence prone to high errors and required more effort in configuring the mapping. With JPA, Hibernate simplified the process of mapping by enabling the scanning for JPA annotations. These annotations remove the need to use XML for the mapping.

9. What are the advantages of using Hibernate over JDBC?

JDBC – Java database connection is a standard database connection API which requires database driver code and separate database connection code for each database. JDBC understands only standard SQL queries. With Hibernate framework, the database drivers come preloaded. There is no need to download a different driver each time you change the database. Moreover, Hibernate support SQL as well as HQL. If the developer uses HQL, hibernate takes care of preparing the SQL query for the underlying database using the dialect that has been configured. Additionally, Hibernate also provides managed caching with multiple configurations.

10. Which are some important interfaces provided by Hibernate?

Hibernate using the following important interfaces.

Session(org.hibernate.Session)

Session is a single-threaded and short-lived object created for a communication cycle between the Java application and the database persistence store. It is a wrapper over JDBC java.sql.Connection class and works as a factory for org.hibernate.Transaction. An instance of the class implementing this interface should be created only when it’s necessary and should be destroyed as soon as we are done using it. This object provides the interface between Java core and the hibernate framework for CRUD operations.

SessionFactory(org.hibernate.SessionFactory)
As the name indicates, this interface manages provides function signatures for the creation and destruction of Session objects. The class implementing SessionFactory has an immutable thread-safe cache that is maintained to manage the sessions. Additionally, it maintains a cache of pre-compiled database mappings to ensure faster database operations.

Transaction(org.hibernate.Transaction)
A transaction, as the name suggests, is an interface containing the function definitions for managing a database interaction. A transaction is a short-lived thread that takes care of fetching the data from Java application and delivering it to the database in the form of a query. A transaction is similar to a session that is destroyed after every database transaction.

Configuring Hibernate Framework

11. What are the configurations involved in Hibernate framework?

Hibernate framework is an enormous framework designed to handle almost every database operation for you. To configure such a framework involves multiple entities to be configured. These include:

  • Database credentials
  • Database dialect
  • Database URL
  • Caching levels
  • ORM mapping
  • Connection pool configuration
  • Table creation mode – Create/Update

Hibernate comes with default values for almost every non-database configuration like the Connection pool size, caching levels, table creation mode and others. Thus, despite having so many configurable aspects, it allows to get started with minimal configuration.

12. What is Hibernate configuration file?

Hibernate configuration file includes the database specific configurations that are required to begin database connection using hibernate framework. The configuration file is usually an XML document with the name hibernate.cfg.xml. In case you prefer to use Java based configuration, you need to create a properties file similar to the one shown below.

################### JDBC Configuration ##########################
jdbc.driverClassName=org.mysql.jdbcDriver
jdbc.url=jdbc:mysql://localhost:3306/mydb;shutdown=true
jdbc.username=root
jdbc.password=xxxxxx

################### Hibernate Configuration ##########################
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.generate_statistics=true

This file can be given any name. However, it is necessary to load this configuration in the Java file using this file name. A sample code to load the properties file in the Java configuration is shown below.

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;

@Import({RepositoryConfig.class})
@Configuration
public class AppConfig
{
    //
    @Bean
    public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer()
    {
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setLocation(new ClassPathResource("hibernate.properties"));
        ppc.setIgnoreUnresolvablePlaceholders(true);
        return ppc;
    }
}

It can be noticed that in a Java based configuration, the class code contains few Spring framework classes as well. Thus, this sample belongs to integration of Hibernate with Spring. Notice the annotations carefully over here. These annotations define that the class carries configuration for hibernate.

13. How does Hibernate create the database connection?

Hibernate reads the configured dialect to decide the driver jar to be used. Hibernate comes pre-packaged with the database driver jars. These jars are same as the ones used for connecting to database using JDBC. Based on the dialect, Hibernate dynamically registers the respective driver class and uses the URL and credentials to connect to the database using JDBC in the backend.

14. What are possible ways to configure object-table mapping?

In Hibernate, there are two possible ways to configure the mapping. One of the two ways is to create an XML file defines the mapping between the database column and the class variable. This XML is known as mapping XML. An entry of every such XML needs to be done in the hibernate.cfg.xml in order to ensure that Hibernate recognises and precompiles these bindings.

The other way to configure a bean is to use annotated Java class for the mapping. Annotated Java classes are automatically scanned for as long as the path of the folder is specified in the hibernate.cfg.xml.

15. Which annotation is used to declare a class as a hibernate bean?

The annotation @Entity is used to declare a class as an entity. A simple example is shown below.

@Entity
@Table(name="users")
public class User{
String username;
String password;
}

16. How do I specify table name linked to an entity using annotation?

As it can be seen in the above code, the annotation @Table is used to specify the database table name linked to the entity.This entity requires a mandatory attribute name which specifies the table name as in the database.

17. How does a variable in an entity connect to the database column?

By default, Hibernate looks for the column names matching the variable names in the class. However, it is also possible to specify different variable names and bind them to respective columns in the database.

18. How do we specify a different column name for the variables mapping?

The annotation @Column is used to define a column name associated with a variable. In absence of this annotation, Hibernate precompiles the mapping of variable mapped to the column with same name. An example of using this annotation is shown below:

@Entity
@Table(name="users")
public class User{
@Column(name="user_name")
String username;
String password;
}

The name attribute is a mandatory attribute to specify the column name different from the variable name. From the above code, it can be understood that the column user_name is bound to the variable username

19. How do we specify a variable to be primary key for the table?

Hibernate is able to create the database tables for an application directly based on the mappings that are provided in the Java code. In such a scenario, Hibernate requires to know which columns are expected to be primary keys. This can be configured using the annotation @Id. Hibernate not only takes care of creating this column as primary key column but also validates its unique constraint during every database insertion and update.

20. How do we define the primary key value generation logic?

The primary key values can be generated using various methods depending on the database. For instance, in MySQL database the primary keys can be generated using an auto-incrementing algorithm while in Oracle database, you need a sequence to be created and used for an auto-incrementing the value for primary key. These methods of generation can be specified using the below annotation code.

@Entity
@Table(name="users")
public class User{

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
int userid;

@Column(name="user_name")
String username;

String password;
}

The userid column here has been defined as a primary key autogenerated using the identity strategy. The possible values for strategy include:

  • GenerationType.AUTO
  • GenerationType.IDENTITY
  • GenerationType.SEQUENCE
  • GenerationType.TABLE

21. How do you configure the dialect in hibernate.cfg.xml?

The configuration of dialect in xml involves defining of a property with the name hibernate.dialect. A sample XML tag for defining the dialect is shown below:

     
<property name="org.hibernate.dialect.MySQLDialect">
org.hibernate.dialect.MySQLDialect
</property>

22. How to configure the database URL and credentials in hibernate.cfg.xml?

Hibernate framework can be configured using variety of property values. In the above questions, we discussed how to configure the framework using property file. The configuration in XML is quite similar. We just need to create the respective property tags with the names similar to the ones specified in the properties file above. The example of configuration database URL and credentials is provided below.

      <property name = "hibernate.connection.url">
         jdbc:mysql://localhost/mydb
      </property>
      
      <property name = "hibernate.connection.username">
         root
      </property>
      
      <property name = "hibernate.connection.password">
         password
      </property>

On execution of the Java application, the Hibernate framework precompiles the code to connect to the database and creates a connection pool to reduce the overhead of database connection during execution of queries.

23. How to configure the connection pool size?

The connection pool size in Hibernate has two values – the minimum pool size and the maximum pool size. These sizes can be configured using the properties hibernate.c3p0.min_size and hibernate.c3p0.max_size. These properties can be configured in the same way as shown for the database credentials above.

24. How do you configure folder scan for Hibernate beans?

Hibernate folder scanning is a feature supported by Spring. Spring framework provides the support to scan the folders and prepare the mapping in the form of hibernate beans without the need to create hibernate mapping xml. To configure the folder to be scanned using Spring framework with Hibernate, use the below code:

<bean id="sessionFactory"
  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
  p:dataSource-ref="dataSource"
  p:configLocation="WEB-INF/classes/hibernate.cfg.xml"
  p:packagesToScan="com.example.model"
/>

25. How to configure hibernate beans without Spring framework?

In the absence of Spring framework, the configuration of beans is done using the respective mapping xml files. These XML files need to be added in the hibernate configuration xml in order for hibernate to detect them. It is also possible to configure the framework so that it scans for the XML entries. Below code demonstrates how to configure hibernate to scan the bean configuration files.

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
   <session-factory>
   
      <property name = "hibernate.dialect">
         org.hibernate.dialect.MySQLDialect
      </property>
      
      <property name = "hibernate.connection.driver_class">
         com.mysql.jdbc.Driver
      </property>
      
      <!-- Assume test is the database name -->
      
      <property name = "hibernate.connection.url">
         jdbc:mysql://localhost/test
      </property>
      
      <property name = "hibernate.connection.username">
         root
      </property>
      
      <property name = "hibernate.connection.password">
         root123
      </property>
      
      <!-- List of XML mapping files -->
      <mapping resource = "User.hbm.xml"/>
      
   </session-factory>
</hibernate-configuration>

In the above code, the mapping part indicates the hibernate mapping file path for the bean of User class.

Hibernate Caching and implementation

Caching is an important feature that is required for enterprise level applications handling thousands of requests daily. Hibernate framework inherently supposed caching of queries outputs at various levels. These caching levels are configurable to best suite your needs. There are three types of caching levels:

  1. Session Level caching: Session level caching is implemented by Hibernate as a default caching level. This caching features caching of objects in the session. These cached objects reside in the session memory itself.
  2. Second Level cache: The second level cache is responsible to cache objects across sessions. When the second level caching is enabled, the objects are first searched in the cache and later if not found, a database query is executed to search for it. Second level cache will be used whenever the objects are being loaded using their primary key. Second level cache objects also fetch their respective associations and reside in a separate memory stack other than session.
  3. Query Cache: Question Cache is utilized to store the after-effects of a query. At the point when the query caching is turned on, the outputs of the query are put away against the fired query and parameters. Each time the query is let go the store framework checks for the mix of parameters and query. In the event that the outcomes are found in the cache, they are returned, generally a database transaction is started. As should be obvious, it’s anything but a smart thought to reserve an inquiry in the event that it has various parameters, since then a solitary parameter can take various qualities. For every one of these blends the outcomes are put away in the memory. This can result in larger memory utilization.

26. How to configure the Hibernate second level caching?

The hibernate second level caching can be configured using EHCache library. To add the EHCache dependency using maven, use the following dependency code.

<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>4.3.5.Final</version>
</dependency>

This library once added, hibernate framework needs to be configured to use the library for caching. In order to configure the second level caching using EHCache, use the below code.

<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="net.sf.ehcache.configurationResourceName">/myehcache.xml</property>


 

27. What are different states of an entity bean?

An element bean occurrence can exist is one of the three states.

Transient: When a object is never continued or related with any session, it’s in transient state. Transient cases might be influenced diligent by calling save(), persist() or saveOrUpdate(). Steady examples might be influenced transient by calling to delete().

Persistent: When a question is related with a one of a kind session, it’s in persevering state. Any occurrence returned by a get() or load() technique is persevering.

Detached: When a object is already relentless yet not related with any session, it’s in disengaged state. Disengaged occasions might be made determined by calling refresh(), saveOrUpdate(), lock() or replicate(). The condition of a transient or disengaged example may likewise be influenced relentless as another constant case by calling to merge().

28. What is the purpose of Session.beginTransaction()?

In Hibernate, every exchange of data is maintained using a transaction. Whenever a new data exchange is to be started, the function Session.beginTransaction is called to start the transaction.

29. What can be done to completed a transaction in Hibernate?

In order to complete a transaction in hibernate, there can be two actions:

  1. Commit
  2. Rollback

Whenever a transaction is committed, the data exchange is written to the database. In case of rollback, the transaction data is flushed and never written or updated to the database.

30. How do we commit a transaction in Hibernate?

The transaction object in Hibernate can either be committed or rolled back. In order to perform this action, we utilise the below code.

tx = Session.beginTransaction();
...
...
...
//Do something with transaction
...
...
...
tx.commit();

As it can be seen, the function call tx.commit() does the task of committing the transaction to the database. For a rollback, the procedure remains the same. All you need to do is change the function call to tx.rollback().

31. Which are the different types of relationships available in Hibernate mapping?

There are three different types of relationships that can be implemented in hibernate. They are:

  1. One-to-One mapping
  2. One-to-Many mapping
  3. Many-to-Many mapping

32. Which annotation is used to define the mapping in Java files?

In order to define mapping in Java files, there are three different annotations that can be used as needed. The annotations are:

  1. @OneToOne
  2. @ManyToOne
  3. @OneToMany

The usage of the annotations is quite clear. The annotation requires a mandatory attribute mappedBy to identify the related table.

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

A Hibernate Session is an interface between Java code layer and hibernate framework. It is the core interface used for handling database transactions. The lifecycle of a session starts from the beginning of a transaction and ends at the end of transaction.
Starting from JPA 2.0, a Session object can be obtained using the below code that uses EntityManager

SessionFactory sessionFactory = entityManager.getEntityManagerFactory().unwrap(SessionFactory.class);

34. Is it possible to connect multiple database in a single Java application using Hibernate?

Yes. Practically it is possible to connect a single Java application to multiple databases using two separate hibernate configuration files and two separate session factories. These hibernate configuration files contain different dialect configuration pertaining to the respective database. The entities are exclusively mapped to the relevant database configuration. Thus, with two different parallel SessionFactory objects, it is possible to have multiple databases connected.

35. What is a Criteria query in Hibernate?

A criteria query in Hibernate is a complex hibernate query that allows the developer to specify multiple conditions to fetch the data from database using a Hibernate query in the backend. A criteria query is created using a Criteria object. This criteria object is later combined with restrictions to get the final result. A simple criteria query execution is demonstrated in the code below:

Criteria cr = session.createCriteria(User.class);
cr.add(Restrictions.eq("user_name", datsabk));
List results = cr.list();

The above query fetches the list of users with the username attribute having value datsabk. Thus, Criteria class provides the necessary implementation to simplify complex queries using objects.

36. What is lazy loading in Hibernate?

As discussed above, it is possible to map the entities with other entities using annotations in Hibernate. When you fetch such entities, hibernate is able to load the associated entities in two ways. One of them is to load them along with the parent entity. This often is time consuming due to the joins and multiplications of records involved.

The other way of loading is called the Lazy Loading way. Lazy loading means that Hibernate would load the associated entity only when you actually try to access the associated entity values. This not only saves you runtime memory but also speeds up the query.

37. What is load() method of session Object?

This method is used to load a proxy object without actually hitting the database. Thus, it saves you the hit to the database and loads the data from the cache. This is an explicit way to tell hibernate to pick the data from cache.

38. Is Hibernate Session object thread-safe?

The Hibernate session object is a global object used to manage sessions with the database. This object can be passed across threads to exchange data. Thus, it is consumable by multiple thread simultaneously. Hence, it is not a thread-safe object.

39. Does Hibernate support polymorphism?

Yes. Hibernate inherently supports polymorphism. Hibernate classes mainly support its operations via polymorphism itself.

40. How many Hibernate sessions exist at any point of time in an application?

Hibernate session is a shared object. During any point of time, there exists only single shared session object that helps in managing transactions and getting connections from the connection pool. It must be noted that this is true only when a single database configuration is used. In case of multiple database configurations, Hibernate would create a separate session object to maintain the mapping and transactions for the other database.

Conclusion

This is a summary of some of the most important concepts and terminologies used in Hibernate framework. These questions have been answered with the aim to make you interview ready. They capture all the important concepts including the configuration, caching and implementation of hibernate framework. However, there is always more to explore.

Ok, so now you are ready for your interview! Don’t forget to check our Examples dedicated subsection!

If you enjoyed this, then subscribe to our newsletter to enjoy weekly updates and complimentary whitepapers! Also, check out our courses for more advanced training!

You are welcome to contribute with your comments and we will include them in the article!

Last updated on Oct. 15th, 2021

Abhishek Kothari

Abhishek is a Web Developer with diverse skills across multiple Web development technologies. During his professional career, he has worked on numerous enterprise level applications and understood the technological architecture and complexities involved in making an exceptional project. His passion to share knowledge among the community through various mediums has led him towards being a Professional Online Trainer, Youtuber as well as Technical Content Writer.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mauro C Mortoni
Mauro C Mortoni
5 years ago

Congratulations for the initiative

Michael R
Michael R
5 years ago

> 37. Is Hibernate Session object thread-safe?
>
> The Hibernate session object is a global object used to manage sessions with
> the database. This object can be passed across threads to exchange data.
> Thus, it is consumable by multiple thread simultaneously. Hence, it is not a
> thread-safe object.

This answer’s conclusion is right — Session is not thread-safe — but its
supporting details are wrong. The first sentences are describing the
thread-safe SessionFactory (global, shared between threads).

Code Guy
Code Guy
4 years ago

I beg you to please convert the partpart to English – I have done hibernate for many years but I don’t even understand what you’re trying to say. I know the three states you meant to described but you have made it so confusing and ineligible even a veteran can’t understand. “An element bean occurrence can exist is one of the three states. Transient: When a object is never continued or related with any session, it’s in transient state. Transient cases might be influenced diligent by calling save(), persist() or saveOrUpdate(). Steady examples might be influenced transient by calling to… Read more »

Senthil
Senthil
4 years ago

How many Hibernate sessions exist at any point of time in an application? Hibernate session is a shared object. During any point of time, there exists only single shared session object that helps in managing transactions and getting connections from the connection pool. It must be noted that this is true only when a single database configuration is used. In case of multiple database configurations, Hibernate would create a separate session object to maintain the mapping and transactions for the other database. Question: How you are saying only a single shared session at any point of time? Cant there be… Read more »

Back to top button