Interviewer Selected Most Asked Hibernate Interview Questions

In this Page we have collected and explained Most important Hibernate Interview Questions and Answers.

Let us start Preparing.

Hibernate interview questions

Q1). What is hibernate?


Hibernate is an open-source Object-relational mapper (ORM) framework that simplifies the interaction of java applications and databases. Hibernate is open source and lightweight.

It simplifies working with databases like data creation, data manipulation, and data access. As it maps Code with the database, Later if we change the database, we don’t need to change the code. This is the main advantage of using Hibernate.

Q2). What is ORM?


ORM stands for Object-Relational Mapping (ORM). It is a programming technique that is used to develop and maintain a relationship between databases and object-oriented programming languages such as Java, C#, etc.

Q3). What are the advantages of using Hibernate over JDBC?


There are various advantages of using hibernate over JDBC some of written below

  • Hibernate is database independent language and can be used with all databases like Oracle, MySQL, PostgresSQL, etc. where as JDBC is database specific.
  • If we are using Hibernate, we need not to know SQL but for JDBC SQL knowledge is required.
  • Hibernate reduces the boilerplate code like creating the connection and loading the driver class etc whereas in JDBC complete setup is required like creating the connection and loading the driver class etc.
  • Hibernate supports annotation-based inheritance and association mapping but JDBC has no concept of inheritance or association mapping.

Q4). Explain hibernate architecture.


Hibernate is a framework to develop persistence logic of Database software that is independent of the database.

Hibernate architecture includes many objects such as a persistent object, session factory, transaction factory, connection factory, session, transaction, etc.

Q5). Tell some core hibernate Interfaces.


Some core hibernate interfaces are

  • Session Interface
  • Session Factory interface
  • Configuration interface
  • Transaction interface
  • Query and Criteria interface

Q6). What are the different functionalities supported by Hibernate?

  • Hibernate uses HQL( Hibernate Query Language) which makes the database independent.
  • It supports auto DDL operations.
  • Hibernate is an ORM(Object Relational Model) tool.
  • Hibernate can generate Auto Primary Key.
  • It supports Cache memory.
  • Exception handling is not mandatory for hibernate.

Q7). List some of the databases supported by Hibernate.

Ans :

Some list of databases supported by Hibernate are :

  • MySQL
  • PostgreSQL
  • Oracle
  • Microsoft SQL Server Database
  • Sybase SQL Server
  • HSQL Database Engine
  • DB2/NT
  • Informix Dynamic Server
  • FrontBase

Q8) What is a Session in Hibernate?


  • Session is a lightweight object that is created on demand. Session provides the physical connectivity between the applications and the database.
  • Whenever we want to access any data or perform any operations on the database, a session is established. And once the operation is completed session is destroyed.
  • Persistence objects are saved and retrieved by the Session object.
  • Session offers operations like create, read, and delete for instances of mapped entity classes.

Q9) What is a SessionFactory?


  • SessionFactory is a factory of session objects that keeps all DB-related property details that are pulled from either hibernate.cfg.xml or files. 
  • SessionFactory is a heavyweight and threadsafe object that is created when the application starts. As the SessionFactory object is threadsafe it can be used by multiple threads in an application.
  • SessionFactory implementation is created per database in an application. If there is multiple databases in a table then we have to SessionFactory for each database.

Q10) Is SessionFactory a thread-safe object?


Yes, SessionFactory is thread safe object and it can be used by all the threads in an application.

Q11) Tell some technologies that are supported by Hibernate.


Some technologies that are supported by Hibernate are
  • XDoclet Spring
  •  Maven
  •  Eclipse Plug-ins
  • J2EE

Q12) How is SQL query created in Hibernate?


To work with SQL query in Hibernate, we will be using Session.createSQLQuery(String query). This will create an SQLQuery object and execute it.

Suppose you want to read all the Student data from Student Table in Database, We can use the below code

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
SQLQuery query = session.createSQLQuery(“select stu_name, stu_roll from Student”);
List<Object[]> rows = query.list();
for(Object[] row : rows){
Student stu = new Student();

Q13). what is lazy loading in hibernate?


Lazy loading in hibernate means don’t load the child data when the parent date is loading/fetching.

For example, Suppose we have two tables Customer and OrderDetail . A Customer can have multiple orders which is maintained in the OrderDetail table. Now when we load the Customer details then only customer information should be load no Order detail should load.

Q14) What is HQL?


HQL stands for Hibernate Query Language, is an object-oriented query language. It works with persistent objects and their properties whereas SQL works with tables and columns.

HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on the database.

Q15). Difference between SessionFactory.getCurrentSession() and SessionFactory.openSession() methods?

  • openSession() need to flush and close session objects explicitly but getCurrentSession() needs not to flush and close session objects explicitly, it is taken care by Hibernate internally.
  • openSession() won’t require any configuration but getCurrentSession() method requries additional configure in hibernate.cfg.xml file.
  • openSession() is slower than getCurrentSession() in single threaded environment.

Q16). Difference between first-level cache and second-level cache?


  • First-level cache always Associates with the Session object whereas the Second-level cache always associates with the Session Factory object.
  • The first-level cache is a session-level cache but Second level cache is a session factory-level cache.
  • First level cache is enabled by default but the second-level cache is not default.
  • First level cache is available only within a session but Second level cache is available across all session.

Q17). Dfference between and session.persist() method.


  • return type is Serializable object whereas session.persist() method return type is void type.
  • save() is supported by only hibernate whereas persist() is supported by JPA as well.
  • save() method works outside the Transaction boundaries or without the transactions whereas persist() won’t work without the Transactions.

Q18). Differentiate between save() and saveOrUpdate() methods in hibernate session.


  • save() method is used to save the data in the database. If there is similar data available in the table for eg: inserting an id that is already available, It will through exception. It will only save the fresh new data. 
  • Save() returns a Serializable object from which we can get the id and can cast it into Integer.


  • SaveOrUpdate() method is a combination of the save and update method. It first performs a save operation in the database if the record is new. If the record is already present in the database then it will update the database. 
  • SaveOrUpdate() won’t return anything because its return type is void.

Q19). Differentiate between get() and load() in Hibernate session.

  • Both get() and load() methods are used to fetch data for the given identifier in hibernate. 
  • Both methods belong to Hibernate session class. 
  • The Difference is If no row is available in the database or in the session cache for a given identifier Get() method return null, whereas the load() method throws an object not found exception. 
  • get() method is slower in comparison to load() method in hibernate.
  • Use the get() method if you are not sure that data is available, otherwise, if you are sure that data is available then use the load() method.

Q20). What are the states of a persistent entity?


4 stages of persistent entity are

  • New (Transient)
  • Persistent (Managed)
  • Detached (Unmanaged) 
  • Removed (deleted)

Q21). What is the One-to-One association in Hibernate?

  • One-to-One mapping in Hibernate means One instance of an entity is associated with another instance of the other entity.
  • An example of this one-to-one mapping will be One person can have only one passport, and one passport can be associated with only one person.
  • @OneToOne annotation is used in a One-to-One association to map a source entity to a target entity.

Q22). What is the Many-to-Many association in Hibernate?

  • In Many-to-Many associations, in Hibernate multiple instances of an entity can belong to multiple instances of another entity.
  • Annotation @ManyToMany is uses in Many-to-Many associations.
  • For example, A ShoppingCart can have multiple items and A item can belong to multiple shoping cart.

Q23). How do you create an immutable class in hibernate?

There are two ways to create an immutable class in hibernate:
1). Mark a class as mutable=”false” After marking class will be treated as an immutable class. By default, it is mutable=”true”.
2). You can use @Immutable annotations with the class to mark the class as immutable.

Q24). What are the states of the object in hibernate?


In hibernate, An object can have three states: transient, persistent, and detached.

Q25). Explain hibernate mapping file.

Hibernate framework uses Hibernate mapping file to get the information about the mapping of a POJO class and a database table.
Following details contains in mapping information:
  • Information about the mapping of a POJO class name to a database table name.
  • Information about Mapping POJO class properties to database table columns.
Hibernate mapping elements
  • hibernate-mapping: hibernate-mapping is a root element.
  • Class: Mapping of a POJO class to a database table.
  • Id: Primary key or Unique key of the table.
  • generator: Sub element of the id element to automatically generate the id.
  • property: It defines the mapping of a POJO class property to the database table column.

Q26). Difference between setMaxResults() and setFetchSize() of Query.

  • setMaxResults is similar to LIMIT in SQL. setMaxResults returns the number of rows you are setting.
  • For example, in a table, we have 50 rows. setMaxResults(20) will return only 20 rows as result.
  • criteria.setMaxResults(20);
  • setFetchSize is about optimization, Instead of returning all rows at one time, It returns rows in a chunk given in setFetchSize .
  • setFetchSize is NOT implemented by all database drivers.
  • For example in a table, we have 50 rows. setFetchSize(20) will return only 20 rows at a time until reads all rows from a table.
  • criteria. setFetchSize(20);

Q27). Difference between sorted and ordered collection in Hibernate?

  • Sorted collection in hibernate means sorting the collection by utilizing the features provided by the Java collections framework.
  • This sorting happens in JVM memory so If your collection is not large then it is an efficient way to sort otherwise it will throw an Out of Memory error.
  • Order collection is also used to sort a collection by specifying the order-by clause in the query.
  • It is a Good Choice If your collection is very large. It is fast compared to the sorted collection.

Q28). Difference between the transient, persistent, and detached state in Hibernate?


A new instance of a persistent class that is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate.

Student student = new Student();
// student is in a transient state


A persistent instance has a representation in the database, an identifier value, and is associated with a Session. You can make a transient instance persistent by associating it with a Session.

Long id = (Long);
// student is now in a persistent state


Now, if we close the Hibernate Session, the persistent instance will become a detached instance: it isn’t attached to a Session anymore (but can still be modified and reattached to a new Session later though).

//user in detached state

29). Is hibernate prone to SQL injection attacks?


  • Hibernate does not provide 100% security to SQL Injection, one can misuse the api. HQL (Hibernates subset of SQL) won’t have any special that makes it any more or less susceptible.
  • Functions such as createQuery(String query) and createSQLQuery(String query) create a Query object that will be executed when the call to commit() is made. If the query string is written for SQL injection It might hurt the database.

30). Mention some important annotations used for Hibernate mapping.


List of some Hibernate annotations are

All Entity beans annotated with @Entity

public class Student implements Serializable {


Specify the database table name where data will be stored.

@Table(name = "student")
public class Student implements Serializable {

This annotation denotes the column in the table for mapping.

@Table(name = " student ")
public class Student implements Serializable {
@Column(name = "name")
private String name;

Annotate the id column using @Id.

@Table(name = "student")
public class Student implements Serializable {
@Column(name = "id")
private int id;

Let the database generate (auto-increment) the id column.

@Table(name = " student ")
public class Student implements Serializable {
@Column(name = "id")
private int id;

Control versioning or concurrency using @Version annotation.

@Table(name = " student ")
public class Student implements Serializable {
@Column(name = "version")
private Date version;

31). What is hibernate caching? Types of Hibernate Caching.


Caching is a mechanism to enhance the performance of a system by pooling the object in the cache.

Cache is a buffer memory that resides between the application and the database. It stores recently used data to reduce the number of database hits.

There are mainly two types of caching:

  • First Level Cache: Session object holds the first level cache data.
  • Second Level Cache : SessionFactory object holds the second level cache data.

32). What is Dirty Checking in Hibernate?


  • Dirty checking is a feature of Hibernate that avoids time-consuming write actions in database.
  • It modifies or updates fields that need to be changed or updated and keep the remaining fields untouched and unchanged.
  • @DynamicUpdate annotation is used with entity class to access dirty checking. This annotation makes the necessary modifications and changes to the required fields only.