Hibernate Interview Questions And Answers

Most Expected Interview questions.

1. Q : WHAT IS HIBERNATE ?

ANS : It is an open source, light weight, non-invasive, java based ORM Framework. To develop Object based Database Software independent O-R Mapping, persistence logic in all kind of java, JEE and Java Framework apps.

2. Q : WHAT ARE THE MAIN FEATURES OF HIBERNATE?

ANS :

1. Hibernate gives HQL (Hibernate Query Language) as DataBase Software Independent.

2. Hibernate supports lazy loading.

3. Allows to develop objects based persistence logic in standalone environment and also in web application environment.

4. Does not need the heavy weight containers , servers to execute Hibernate Code.

5. Hibernate O-R Mapping solve the mismatches between java programming and DataBase Programming.

6. Hibernate support both XML and annotation based O-R Mapping configuration.

7. It supports two levels of caching to reduce network round trips between hibernate app and Database software. ( cache is a temporary memory that hold data for temporary period).

8. Hibernate supports versioning. (Allows to keep track of how many times the object/Record is modified).

9. Supports Timestamping feature. ( Keep track of when object/ Record is saved or modified with date and time values)

10.Give supports to Native SQL queries to develop persistence logics.

11.Supports object level relationship like one-to-one, one-to-many, many-to-one, many-to-many.

12.Since Hibernate allows to develop object based database software independent persistence logic , we can change DB software in the middle of development / production environment.

3. Q : WHAT IS HIBERNATE CONFIGURATION FILE ?

ANS : It is the file that contains information to establish connection with database software and to provide instructions to Hibernate Framework.

This file contains 3 types of details :

  • 1. Connection Properties.
  • 2. Hibernate Properties.
  • 3. Hibernate Mapping file names.

4. Q : WHAT ARE THREE CORE CONCEPTS OF HIBERNATE FRAMEWORK?

ANS :

  • 1. Configuration
  • 2. SessionFactory
  • 3. Session

1. CONFIGURATION :

When Hibernate Configuration object is created , Hibernate framework will be activated based on the jar file that are added to class path or build path.
This object also reads data and verifies given configuration file and mapping file entries and stores the information as “in-memory metadata” at RAM-Level in form of Hashmap object.
Now onwards if configuration file , mapping file information required during execution of application . It will collect from that “In-Memory metadata” (Hashmap) instead of going those physical XML files.
Example :
— — — —
// Activate Hibernate Framework
Configuration cfg = new Configuration();
// Verify and Read both configuration file ,Mapping file data and store the data as in memory metadata
cfg = cfg.configure(“/hibernate.cfg.xml”);

2. SESSIONFACTORY :

It will be created based on Configuration object. This Object holds connection properties, hibernate configuration file information, mapping file information and other details so it is called heavy weight object in Hibernate programming.
It is immutable object. i.e. once the data placed in that object it can not be modified.
It is thread safe object because all immutable objects are thread safe objects by default.
It is a factory to create hibernate Session objects.
Example-:
— — — —

SessionFactory factory = cfg.buildSessionfactory();

3. SESSION :

Sessionfactory object gets one connection object from its JDBC connection pool and uses that object to create Hibernate Session Object.
This object Open Connection between Java Application and DataBase Software through Hibernate Frameworks.
It is the base object for programmer to give persistence instructions to hibernate framework using Domain class objects.
It is not thread safe object by default.
Example :
— — — —
Session session = factory.openSession();

5. Q : WHAT IS HIBERNATE DIALECT ?

Ans : It is an optional property of hibernate configuration file but it is recommended property to use.
It helps the Hibernate Framework to decide the destination DataBase Software to communicate.
It helps hibernate framework to generate optimized SQL as required for underlying DB Software.

6. Q : What is difference between session.save() and session.persist() methods ?
ANS :
session.save() :

It is used to return the generated identity value.
session.persist() :
It does not return the generated identity value because its return type is void.

signatures :
public Serializable save(Object obj);
public void persist(Object obj);

7. Q : What is the difference between session.load() and session.get() method ?
ANS :
session.get() :

1. Perform early/eager loading.
2. Does not create any proxy object.
3. Create only object for domain class to load single record.
4. Does not throw any exception If record not found.
5. Suitable to check wheather record is available or not.
6. Use this method when loaded record will be used immediately.

session.load() :
1. Perform lazy loading.
2. It will create proxy object.
3. It will create two objects (Proxy + Read object) for domain class to load single record.
4. It will throw an exception if record not found i.e. ObjectNotFoundException.
5. Not Suitable to check whether record is available or not. If sure about record is available then only use.
6. Use this method when loaded record will be used lately.

8. Q : What is the difference between session.save() or session.saveOrUpdate() methods ?
ANS :
session.update() :

It is used to just update the records by using update SQL query.
session.saveOrUpdate() :
It is used to update the record If record is already available, otherwise it will insert the record. For this it internally
generate select query and insert/update query.

9. Q : What is the difference between session.saveOrUpdate() and session.merge() methods ?
ANS :
session.saveOrUpdate() :
It does not return any object representing the record that will inserted or updated because its return type is void. If we call session.saveOrUpdate() to update the object with same identity value that is already there in first level cache of session object then we will get Exception.(NonUniqueObjectException).
session.merge() :
It return object representing the record that will inserted/updated. If we call session.merge() to update the object with same identity value that is already there in first level cache of session object then no exception will raise , Moreover given object modification will be synchronized with database table records.

NOTE : If you modify same record by loading the record or object in multiple sessions then to merge all modifications and reflect the changes to database table use session.merge() method.

10. Q : What is cache and Types of cache in Hibernate?
ANS : Cache is a temporary memory that holds data for temporary period.
In Client-Server environment the cache at client side holds data given by server and uses that data across the multiple
same request to reduce the round trips between client and Server.

Hibernate Support Two Types Of Cache :
=====================
1. First Level Cache/L1 Cache/Session Cache
2. Second Level Cache/L2 Cache/SessionFactory Cache

11. Q : What is First Level Cache/L1 Cachce/Session Cache in Hibernate ?
ANS :
L1 Cache is associated with session object on 1 per session object basis. It is built in cache for every session object the data of one session cache can not be used in another session cache.

Hibernate uses L1 cache in two cases :
===================
1.
When we ask hibernate to load same object/record from database for multiple times.

It will load that record only 1 time from database and keeps that object in L1 Cache to use it for multiple times.
This avoids multiple SQL queries generation, Object creation and also reduces network round trips.

Example :
=====

Employee emp1 = (Employee) session.get(Employee.class, 1); [hit-1]
System.out.println(emp1);
Employee emp2 = (Employee) session.get(Employee.class, 1); [hit-2]
System.out.println(emp2);
Employee emp3 = (Employee) session.get(Employee.class, 1); [hit-3]
System.out.println(emp3);

In this example , the hit will goes to Database for 1 times by generated 1 select query and uses that object for multiple times by keeping in L1 Cache.

for First hit [hit-1] gets record from database and keeps in L1 cache.
for second hit [hit-2] gets record from L1 cache.
for third hit [hit-3] gets record from L1 cache.

2. In a transaction if persistent state object is modified for multiple times. Instead of generating multiple update queries to reflect the modifications in database table, It will keep track of all the modifications of that object in L1 Cache till the end of Transaction.
Once the transaction is committed it generates only one update query having all the modification to reflect the modifications in database table.

Example:
=====
Employee emp = (Employee)session.get(Employee.class, 1);
Transaction tx = null;
try{
tx = session.beginTransaction();
emp.setAddress(“city-hyd”);
emp.setAddress(“city-blr”);
emp.setLastName(“rao”);
tx.commit(); // it will generate update query here having all modifications.
}Catch(Exception ex){
tx.rollback();
}

12. Q : How to control L1 cache in hibernate?
ANS :
session.evict(emp); // remove single object from L1 Cache.
session.clear(); // removes all objects from L1 Cache.
session.close(); // close L1 Cache along with session.

13. Q : Why we need “hibernate.hbm2ddl.auto” property ?
ANS :
Hibernate allows to create/alter Database tables based on configuration done in hibernate mapping files.

This option is useful to add new columns in the middle of project development or in the production environment of the project.

This property is also useful to create database tables dynamically. If the database is changed in the middle of project development or in the producation environment dynamically.

It is Recommended do not use this option to design database table of project because this will be taken care by database designing team before coding of the project.

This property has four different values :
— — — — — — — — — — — — — — — —
1. create
2. update
3. validate (default)
4. create-drop

14. Q : What are the different states of object in hibernate?
ANS :

There are three different states of object in hibernate.

1. Transient State.
2. Persistent State.
3. Detached State.

1. Transient State :
==========

The object is in transient state if it is just assigning null value or created but has no primary key (identifier) and not associated with session.

Example :
=====

Employee emp = null; // object in transient state
Employee emp = new Employee(“”,””); // object in transient state

We can make Object transient state as persistant state by calling save(), persist(), update(), saveOrUpdate(), merge(), get(),load() methods.

We can make object persistant state as Transient state by just calling delete() method.

2. Persistent State :
==========

The object is in persistent state if Object is associated with session, and you just saved the instance in the database or retrieved the instance from the database.

Example :
======

Employee emp = new Employee(“”,””); // Object in Transient state.
Transaction tx = session.beginTransaction();
session.save(emp); // Object in persistant state.
tx.commit();

Persistent state Object reside in first level cache/L1 Cache of session.

3. Detached State :
==========

The object is in detached state if session is closed.
By calling session.close(), evict() or clear() methods we can make persistant state object as Detached State Object.

15. Q : What is Object Versioning and How to enable it ?
ANS :

The process of keeping track of how many times, the loaded object is modified through hibernate persistance logic is known as versioning.

To implement this feature in our project we just need to add “@Version” annotation in our entity class.
Example :
=====
@Version
@Column(name=”ver_col”)
private int version;

16. Q : What is Timstamp feature in hibernate and How to enable it ?
ANS :

The process of keeping track of when each object/record is inserted or updated. It holds the date and time of record/object insertion or updation.

To implement this feature in our project we just need to add “@Temporal” annotation in our entity class.
Example :
=====
@Temporal(TemporalType.Date)
@Column(name=”modified”)
private Date modified = new Date();

17. Q : What is composite Identity field ?
ANS :
If primary key constraint is applied on multiple column of database table then it is called composite primary key constraint.

18. Q : What are Generators in Hibernate?
ANS :
Hibernate gives set of pre-defined algorithms as identity value generator to generate identity value for hibernate domain class object while saving them to database.

All the generator classes implements the org.hibernate.id.IdentifierGenerator interface. The application programmer may create one’s own generator classes by implementing the IdentifierGenerator interface. Hibernate framework provides many built-in generator classes:

1. assigned
2. increment
3. sequence
4. hilo
5. native
6. identity
7. seqhilo
8. uuid
9. guid
10. select
11. foreign
12. sequence-identity

19. Q : Which one is the default generator in hibernate ?
ANS :
Assigned Generator is the default generator if no generator is configured.

20. Q : What is the difference between identity and increment generator in hibernate ?
ANS :
Identity :
=====
1. It is database software dependent.
2. Id field mapped column must have auto increment constraint.
3. consider deleted value while generating new id value.
4. Database software use id value after inserting record.

Increment :
=======
1. It is database software independent.
2. Id field mapped column not required.
3. Deleted value does not consider while generating new id value.
4. Hibernate software generate id value.

21. Q : Why we need custom generator in hibernate ? How to create custom generator in hibernate ?
ANS :
If we are not feeling comfortable with pre-defined generators then we can create user-defined generator.

To create Custom-Generator, We need to implement IdentifierGenerator(Interface).

Example :

package com.custom.generators;

import java.io.Serializable;
import java.sql.*;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;

public class DepartmentIdGenerator implements IdentifierGenerator{

@Override
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {

String prefix = “DEP”;
Connection connection = session.connection();

try {
Statement statement=connection.createStatement();

ResultSet rs=statement.executeQuery(“select count(Department_Id) as Id from demo.Department”);

if(rs.next())
{
int id=rs.getInt(1)+101;
String generatedId = prefix + new Integer(id).toString();
System.out.println(“Generated Id: “ + generatedId);
return generatedId;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}

SessionImplementor :
Contract between session object and other parts of hibernate framework.
Object :
It represent hibernate domain class object.

22. Q : What is HQL ?
ANS :

HQL stands for Hibernate Query Language.
It is object based query language. It is databse software independent query language. It support both select and non-select operations. These queries will be written based on domain class and its properties.

Every HQL query will be converted into SQL query by hibernate using ASTQueryTransaltorFactory.
It supports both positional params (?) and named params (:<name>)
Each HQL query will be represented by Query object. It is the object of java class that implements org.hibernate.Query(I). Gives support for conditional classes , relational operators, joins, aggregate functions, sub queries etc.
Use list() or iterate() method to execute HQL select query and use executeUpdate() to execute HQL non-select query.
We can not perform DDL operations( create, alter, drop, truncate, rename)
HQL degrades the performance little bit in the process of generating SQL queries internally.

23. Q : What are the difference between list() and iterate() methods in HQL?
ANS :

list() :
1. Generate 1 select query to get n-records.
2. perform early loading of an object.
3. Does not create any proxy object.
4. Gives list of collection.
iterate():
1.Generate 1+n select query to get n-records.
2. perform lazy loading of object/record.
3. It will create proxy objects.
4. Gives iterator object pointing to list collection.

24. Q : What is Criteria in hibernate ?
ANS :

It is used to generate optimized sql queries to improve the performance based on QBC(Query By Criteria) Logic.
This is very useful in pagination and report generation.
Allow to perform both single row and bulk operations.
QBC logic will be developed without any query support.
QBC can be used to retrive single or multiple specific column values.
supports to perform aggregate operations.
Does not support non-select operations.

25. Q : What are the inheritance mapping strategies ?
ANS :

To Overcome sub type problems nothing but mapping classes of inheritance with one or more database table we can use “Inheritance Mapping”.
These are different types of Inheritance mappings :
1. Table per class hierarchy
2. Table per subClass
3. Table per concrete class

1. Table per class hierarchy :
— — — — — — — — — — — —

@Inheritance(Strategy = InheritanceType.SINGLE_TABLE)
All the classes of inheritance will be mapped with single database table.
Database table contains columns to store the property values of super classes and sub classes. Database table can have descriminator column to know which record is inserted by using which domain class and column will not be mapped with any property.

Limitations :
=======

1. We need to take big table with huge number of columns to hold the values of all the classes inheritance hierarchy . This is against of read world database design.

We can not apply not null constraint on the columns of sub classes property.
To work with descriminator column values we need to use native SQL support.
2. Table per subClass :
— — — — — — — — —

@Inheritance(Strategy = InheritanceType.JOINED)
Every class of inheritance hierarchy will have own database table but all these database tables participates in relationship.
The database table of super class and database table of subclasses will be placed in association (one-to-one) thorough foreign key column.

3. Table per concrete class :
— — — — — — — — — — — —

@Inheritance(Strategy = InheritanceType.TABLE_PER_CLASS)
In this strategy Every class of inheritance hierarchy will have its own database table but these database tables will not be there in association, moreover the database tables of subclasses will maintain columns representing super class properties and their sub class properties.

In the above discussion there is possibility having duplicate columns in multiple databse table which is against of industry standard.

26. Q : What are the mapping associations used in hibernate?
ANS :

Why we need :
Storing the data of multiple entities in single database table gives lots of problems.
They are :
1. Data Redundancy problem.
2. Complexity in managing huge amount of data.

Storing user and phone details in single table gives problems.
Table : User_Phone_Info
Columns : user_id, first_name, last_name, address, phone, number_type, provider

Solution 1:
— — — —

Maintain user details and phone number details in separate table.

Table : User
Columns : user_id, first_name, last_name, address
Table : Phone_numbers
Columns : phone, number_type, provider

Limitation :
======

Though 2 tables are taken, since they are not placed in relationship, So we can not access user details from phone_numbers and phone_numbers from user.

Solution 2 :
— — — — —

This solution has solve the problem and the limitations of solution 1. In hibernate programming we need to take domain classes participating in relationship when their database tables are in relaionship , due to this we can navigate from one object to another object of domain classes.

Hibernate support 4 model of Association mapping :
=========================== =

1. One-To-One
2. One-To-Many
3. Many-To-One
4. Many-To-Many

27. Q : What is cascading in Hibernate ?
ANS :

The process of navigating/propagating non-select persistence operations performed on the main/parent object to the associated child object is called cascading.
These are the possible values :
================

cascade = “none” → Any persistence operation on main object does not cascade to associated object.
cascade = “persist” → cascade insert operation to associated object.
cascade = “save-update” → cascade insert and update operations to associated object.
cascade = “delete” → cascade the delete operations to associated objects.
cascade =”merge” → cascade the merge operations to associated objects.
cascade =”all” → cascade insert,update, delete operations to the associated object.
cascade = “delete-orphan” — -> cascade the delete operations and also deletes the orphan records.
cascade=”all-delete-orphan” → cascade all the persistence operations and also deletes orphan records.

28. Q : What is “inverse” association in hibernate ?
ANS :

While working with bi-directional association, you can keep inverse =”true” to tell to hibernate the other side association is mirror of current side.
This helps hibernate to generate SQL queries appropriately by keeping Bi-Directional association in mind and avoids the generation of unneccesary additional queries to update the for key column values.

29. Q : What is HQL joins? Types of HQL joins?
ANS :

We use SQL joins to get records from more than one table by using single select SQL query with implicit conditions.
To work with SQL joins database table need not be there in relationship.

=> To get more than 1 domain class objects by using single HQL select query we can use HQL joins. These joins internally use some implicit conditions to fetch the data.
To work with HQL joins our domain classes must be there in relationship like one-to-one, one-to-many, many-to-one and many-to-many.

Hibernate support 4 types of joins :
==================

1. inner join (default)
2. left join | left outer join
3. right join | right outer join
4. full join.

1. Inner Join :
========

Gives the common data of left side table and right side table.
2. Left Join :
======

Gives common data of both tables and also gives uncommon data of left side table.
3. Right Join :
========

Gives common data of both tables and also gives uncommon data of right side table.
4. Full Join :
======

Gives both common and uncommon data of both tables.

30. Q : What is (1+N) Problem ? How to solve (1+N) Problem ?
ANS :

In one-to-many association the hibernate framework generate 1 select query to retrive all parent records. and n-select queries to retrive child records of n-parent record that means it generate (1+N) select queries.
Generating more queries degrade the performance of the application.

To Resolve (1+N) problem :
==============

solution 1:
— — — —

By using “fetch” joins.
Example :
=====

String query =”select u from User u inner join fetch u.phones”;
Fetch Join disable lazy loading and enables early loading by generating single SQL select query to get all parent table records and the associated child table records.

Solution 2 :
— — — — —

By Using QBC with FetchMode.JOIN
Criteria ct = session.createCriteria(User.class);
ct.setFetchMode(“phones”, FetchMode.JOIN);
List<User> list = ct.list();

31. Q : What are the different fetching strategies in Hibernate ?
ANS :

There are 3 fetching strategies.

1. Select
2. SubSelect
3. Join


1. Select :
=====

Generate 1 select query to get all parent records and generate n-select queries to get child records of n-parent records. Raise (1+N) select problem.

2. SubSelect :
=======

Generate 1 select query to get all parent records and 1 select query to get child records (1+1) queries. Does not raise (1+N) select problem.

3. Join :
====

Generate 1 select query to get all parent records and the associated child records. Solve (1+N) select problem.

32. Q : What is Second Level Cache/L2 Cache/SessionFactory Cache in hibernate ?
ANS :

Hibernate support cache to reduce network round trip between client and server.
Second Level cache is configurable cache associated with SessionFactory object. It is 1 per sessionFactory Object.

The following second level cache software are available.
1. EhCache
2. Swarm Cache
3. OS Cache
4. tangosol Coherence Cache


We need to specify concurrency strategy towards placing object and retriving object from L2 cache.
They are :
a) Read-Only
b) Read-Write
c) NonStrict Read-Write
d) Transactional

We can specify caching strategy through annotation at the top of the domain class by using @Cache annotation.

Example :
=====

@Cache(usage=CacheConcurrencyStrategy.Read-Only)
@Entity
@Table(name =”Employee”)
public class Employee{
}

33. Q : What is Transaction Management in Hibernate?
ANS :

The process of combining related operations into single unit and executing them by applying do everything or nothing principle is called transaction management.

While working with Transaction Management 3 operations are important :
1. Begin Transaction
2. Continue Transaction
3. Commit or Rollback Transaction

If only single resource is involved in transaction management operation then it is called Local Transaction.

If more than one resource is involved in Transaction Mnaagement operation then it is called Global Transaction.

Hibernate does not support Global Transaction .

34. Q: What is pagenation ?
ANS :

The process of displaying huge amount of records part by part in multiple pages is called pagenation. This is very useful in report generation. We generally do report generation by using criteria api with the support of setFirstResult() method and setMaxResult() method.

Example :
=====

Criteria ct = session.createCriteria(Employee.class);
ct.setFirstResult(0);
ct.setMaxResult(9);
List<Employee> list = ct.list();

35. Q : What is Locking in Hibernate?
ANS :

If multiple client application/threads access records of database table simultaneously or concurrently then there is a possibility of data corruption.

To solve this concurrency problem we need to use locking concept of hibernate.

Two Types of locking in hibernate :
— — — — — — — — — — — — — —


1. Optimistic Locking :
— — — — — — — — —

Use versioning feature of hibernate for this locking.
This locking throws exception if the version of the object that is there with client application is not matching with the version of record that is there with database table.
The exception will be raised i.e. staleStateException .
2. Pessimistic Locking :
— — — — — — — — —

In this locking if one client access the record then lock will be applied on the record. So other client can not access the records simultaneously until the lock is released.
For this we need to use Session.get(-,-,-) by specifying the LockMode as UPGRADE_NOWAIT.

Pessimistic lock is recommended.
No versioning is required.

NOTE :
===

If we execute any application by enabling versioning feature. The optimistic Lock will be applied automatically.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store