Top 50 Hibernate Interview Questions and Answers - Frequently Asked - 2022

1. What is Hibernate?

Hibernate is the most popular open-source Java ORM framework in use today. Hibernate allows you to map plain old Java objects to relational database tables. Hibernate also provides data query and retrieval facilities. Hibernate generates the SQL calls and attempts to relieve the developer from manual result set handling and object conversion and keep the application portable to all supported SQL databases. 


2. What is ORM?

ORM sets the mapping between the set of objects which are written in the preferred programming language like Java and relational database like Oracle. It hides and encapsulates the SQL queries into objects and instead of SQL queries, we can use directly the objects to implement the SQL query.



3. What are the major advantages of Hibernate Framework?

  • Hibernate framework is an open-source framework. 
  • Hibernate framework is a high-performance framework because of its internal cache.
  • Provides facilities to automatically create a table.
  • It provides a database-independent query language HQL (Hibernate Query Language).
  • HQL (Hibernate Query Language) is more object-oriented and close to Java.
  • Maintenance is easy and cost-effective.
  • Reduces repeat code
  • The lazy-loading concept fetches only the necessary object that is required for the execution of an application.
  • Versioning
  • It supports relationships like One-To-Many, One-To-One, Many-To-Many-to-Many, Many-To-One.


4. Draw hibernate architecture?



5) What are the core interfaces of Hibernate? 

  • Configuration 
  • SessionFactory 
  • Session 
  • Query 
  • Criteria 
  • Transaction


6) Explain Hibernate Configuration?

Hibernate Configuration allows a Java application to specify configuration parameters used in the application. As Hibernate is designed to serve in different environments, it needs a broad range of configuration parameters. These configuration parameters contain the information of the database connection, transaction, cache, and other properties. Hibernate provides the configuration in two ways, an XML file (hibernate.cfg.xml) or by setProperty method (like hibernate.properties).


7) What is SessionFactory in hibernate?

SessionFactory can be created by providing Configuration object, which will contain all DB related property details pulled from either hibernate.cfg.xml file or hibernate.properties file. SessionFactory is a factory for Session objects. With a Session, a developer can perform create, update, retrieve or delete operations. The SessionFactory bootstraps the entire data persistence layer at startup as it handles important database connectivity tasks, connection pooling, thread pooling, JNDI interactions and even database table creation if persistent entities require it.


8) What is Session in Hibernate?

The session provides a physical connection between the application and the database. The Session will be established each time the application wants to do something with the database. Session object will be provided by SessionFactory object. All the persistent objects will be saved and retrieved through the Session object. Sessions also specifically contain Factory Methods to return Transaction, Query, and Criteria Objects. The session object must be destroyed after using it.


9) What is Hibernate Query?

The Hibernate Query object is used to retrieve data from the database. We can use either SQL or Hibernate Query Language (HQL). To create any query we need to obtain the Session object which is used to create new database entities.


	Session session = SessionFactory.getCurrentSession();


10) What is HQL Query?

The HQL (hibernate query language) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries.

HQL Query example:

	String hqlQuery = "from User";
Query query = session.createQuery(hqlQuery); List userList = query.list();


11) What is the difference between HQL and SQL Query?

HQL is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. This is the main difference between HQL and SQL.

HQL Query example:

	String hqlQuery = "from User";
Query query = session.createQuery(hqlQuery); List userList = query.list();

SQL Query example:

	String sqlQuery = "from User";
SQLQuery query = session.createSQLQuery(sqlQuery); List userList = query.list();


12) What is the Criteria in Hibernate?

The Hibernate Criteria provides an elegant way of building dynamic queries on the persistence database. The hibernate criteria API is a very Simplified API for fetching data from Criterion objects. The criteria API is an alternative to HQL queries. It is more powerful and flexible for writing tricky criteria functions and dynamic queries. The primary advantage of the Criteria API is that it is intuitively designed to manipulate data without using any hard-coded SQL statements.

Criteria example:
Criteria criteria=session.createCriteria(Supplier.class); 
List<Supplier> suppliers=criteria.list();


13) What is transaction management in hibernate?

The transaction is an interface available in org.hibernate package which is associated with the session. In the transaction, if any single step fails, the complete transaction will be failed. We can describe transaction with ACID properties. ACID refers to the four key properties of a transaction: atomicity, consistency, isolation, and durability.

1. Atomicity – All success or none. 
2. Consistency – Database constraints should not be violated. 
3. Isolation – One transaction should not affect another one. 
4. Durability – It should in the database after the commit.

Creating transaction object
Session session = factory.openSession();
Transaction transaction = session.beginTransaction();

Transaction object further can be used to call commit() or rollback() method.


14) What does persistence object mean in Hibernate architecture?


Persistent objects are instances of POJO classes that you create that represent rows in the table in the database. When a POJO instance is in session scope, it is said to be persistent i.e hibernate detects any changes made to that object and synchronizes it with the database when we close or flush the session. 


15) Name the states that a persistent entity exists in?


Persistent entities exist in only three states: 
  • Transient 
  • Persistent 
  • Detached


16) Describe the differences between Hibernate’s transient, persistent, and detached states? 

  • Transient - 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:
	User user = new User(); 
user.setUserName("Dummy user"); // user is in a transient state

  • Persistent - 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) session.save(user); 
// user is now in a persistent state

  • Detached - 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).
        session.close(); //user in detached state



17) Mention some of the databases that Hibernate supports?

Hibernate supports all the major RDMS. Following are the list of database engines supported by Hibernate: 
  • HSQL Database Engine 
  • DB2/NT 
  • Oracle 
  • Microsoft SQL Server Database 
  • Sybase SQL Server 
  • Informix Dynamic Server 
  • MySQL 
  • PostgreSQL 
  • FrontBase


18) What is one to one association in Hibernate?

The one-to-one relation specifies that an entity(User) is associated with only a single instance of another entity(PanCard). From a database perspective, you can assume that if table User has a one to one mapping with table PanCard, then each row of Table PanCard will have a foreign key column which refers to a primary key of Table User.


19) What is one to many association in Hibernate?

The one-to-many mapping means that one row in a table can be mapped to multiple rows in another table. For example, think of an Address system where we have another table for User. An Address can have multiple address, so here we have one to many mapping.


20) What is many to one association in Hibernate?

A many-to-one association is the most common kind of association where an Object can be associated with multiple objects. For example, the same address object can be associated with multiple student objects.


21) What is many to many association in Hibernate?

The many-to-many mapping in hibernate is required when each record in an entity may have many linked records in another entity and vice-versa.
For example, a customers can purchase various products, and products can be purchased by many customers.


22) What is lazy loading in Hibernate?

Lazy loading means when the select query is executed it will not hit the database. It will wait for the getter function i.e when we required then, it will fetch from the database. Lazy loading improves performance by avoiding unnecessary computation and reduce memory requirements.


23) What are the differences between openSession and getCurrentSession in hibernate?

Lazy loading means when the select query is executed it will not hit the database. It will wait for the getter function i.e when we required then, it will fetch from the database. Lazy loading improves performance by avoiding unnecessary computation and reduce memory requirements.

Parameter
openSession
getCurrentSession


Session object
It always creates a new Session object
It creates a new Session if not exists, else uses the same session which is in the current hibernate context



Flush and close
You need to explicitly flush and close session objects
You do not need to flush and close session objects, they will be automatically taken care of by Hibernate internally

Performance
It is slower than getCurrentSession in a single-threaded environment, 
It is faster than getOpenSession in single-threaded environment,



Configuration
You do not need to configure any property to call this method
You need to configure additional property “hibernate.current_session_context_class” to call getCurrentSession method, otherwise it will throw exceptions.


24) What is the dialect in hibernate?

The Language which is used by the databases for communication is called Dialect. Every database has its own dialect, as in, it varies from database to database. For example, the query syntax of PostgreSQL varies with that of DB2.


25) What is the difference between persist() and save() in Hibernate?

Persist() 
  • Does not return generated Id after saving. Its return type is void.
  • Does not save the changes to the database outside of the transaction. 
  • Assigns the generated Id to the entity you are persisting
  • session.persist() for a detached object will throw a PersistentObjectException, as it is not allowed.

Save() 
  • Returns generated Id after saving. Its return type is Serializable.
  • Saves the changes to the database outside of the transaction.
  • Assigns the generated id to the entity you are persisting.
  • session.save() for a detached object will create a new row in the table. 


26) How can we increase the performance of a Hibernate application?

  • Tuning JVM memory settings
  • Optimizing the configuration of JDBC datasource and Hibernate
  • Optimizing Hibernate mappings
  • Optimizing Hibernate Session management
  • Adding missing DB indexes
  • Improving SQL statements
  • Refactoring java code


27) What is the "N+1 selects problem" in Hibernate?

N+1 problem is a performance issue in Object Relational Mapping that fires multiple select queries (N+1 to be exact, where N = number of records in a table) in the database for a single select query at the application layer.


28) Is Hibernate Session a thread-safe object?

No, Session is not a thread-safe object, many threads can't access it simultaneously. In other words, you cannot share it between threads.


29) Is Hibernate SessionFactory a thread-safe object?

The internal state of SessionFactory is immutable, so it’s thread-safe. Multiple threads can access it simultaneously to get Session instances.


30) What is difference between Hibernate Session get() and load() method?

The internal state of SessionFactory is immutable, so it’s thread-safe. Multiple threads can access it simultaneously to get Session instances.



31) Explain the save() method in Hibernate?

The save method persists an entity. It assigns an identifier if the entity doesn't exist in the database. If exists, the save method performs an update. In both cases save method returns the generated ID of the entity.


32) Explain the update() method in Hibernate?

Update method updates the existing object using the identifier. If the identifier does not exist, it throws an exception.


33) Explain the saveOrUpdate() method in Hibernate?

Calls either save() or update() on the basis of identifier exists or not. e.g if identifier exists, update() will be called or else save() will be called.


34) Explain the merge() method in Hibernate?

The merge() method is used when we want to change a detached entity into the persistent state again, and it will automatically update the database. The main aim of the merge() method is to update the changes in the database made by the persistent object.


35) Difference between save() and persist()?

Key
save()
persist()


Return Type
It stores object in the database. The return type of the save() is a Serializable object
It stores object in the database. The return type of the persist() is void.



Transaction Boundaries
Save the changes to the database outside of the transaction
Does not save the changes to the database outside of the transaction

Detached Object
session.save() for a detached object will create a new row in the table
session.persist() for a detached object will throw the PersistentObjectException as it is not allowed



Supported by
save() is only supported by Hibernate
persist() is supported by both JPA and Hibernate



36) What are the different types of caches available in Hibernate?

Hibernate offers three caching levels: 

1. First-Level Caching
2. Second-Level Caching
3. Query-Level Caching


37) What is First-Level Cache in Hibernate?

The First-Level cache is the session cache. Objects are cached within the current session and they are only alive until the session is closed.


38) What is Second-Level Cache in Hibernate?

The Second-Level cache is an optional caching against the previous type of cache and is used in case the application could not locate inspected data in the first level cache. If data is missed from the first level cache then that data entity is being looked up in the second-level cache. The second level cache exists as long as the session factory is alive. Keep in mind that in the case of Hibernate, the second-level cache is not a tree of objects; object instances are not cached, instead it stores attribute values.


39) What is Query-Level Cache in Hibernate?

The Query-Level Caching is optional caching which requires more physical cache memory to be added to the setup. In case we have some complex data-intensive queries running at the regular interval of times that require fetching data using the same parameters then we can have this cache added to our system to fasten the query results as these results will be stored already in the query cache.


40) What is JPA? How is Hibernate related to JPA?

JPA, which is actually known as Java Persistence Application Programming Interface OR Java application programming interface, is used to manage the relational data. JPA is basically is a specification. It deals with the object or relational metadata. The language of the JPA is JPQL (Java Persistence Query Language). Hibernate is an implementation of the JPA specification. All annotations specified by JPA are implemented by Hibernate. 


41) How can you generate a unique identifier using Hibernate?

Hibernate can create identifier values automatically. There are several identifier generation strategies. Some of them are,
  • IDENTITY − In identity, the database is responsible to auto-generate the primary key. Insert a row without specifying a value for the ID and after inserting the row, ask the database for the last generated ID. It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HSQL.
  • SEQUENCE − In sequence, we first ask the database for the next set of the sequence then we insert a row with return sequence id.
  • CUSTOM GENERATOR - If we want to generate a primary key with our format, then we can go to this custom generator.
  • AUTO -  Selects one of the above based on the database.


42) What is optimistic locking?

In this locking, the concurrent changes are avoided by using the versioning object. Version checks the version numbers or the timestamps to detect conflicting updates and to prevent lost updates.


43) What does Automatic Dirty Checking mean?

Dirty Checking is one of the features of Hibernate. In dirty checking, hibernate automatically detects whether an object is modified (or) not and need to be updated. As long as the object is in a persistent state i.e., bound to a particular Session(org.hibernate.Session). Hibernate monitors any changes to the objects and executes SQL. For dirty checking to work, the object must exist in the cache.

The dirty checking feature of Hibernate reduces writing time by updating only the fields requiring changes and leaving other fields intact.


44) What is meant by JDBC?

JDBC or Java Database Connectivity gives a set of Java APIs to access relational databases from a Java program.


45) What Are The Important JPA Annotations Used For Hibernate Mapping?

  • javax.persistence.Entity – The @Entity annotation is used to mark this class as an Entity bean. So the class should at least have a package scope no-argument constructor.
  • javax.persistence.Table – The @Table annotation is used to specify the table to persist the data.
  • javax.persistence.Access – It is used to specify the access type, field, or property. The default value for this annotation is the field.
  • javax.persistence.Id – It defines the primary key in the entity bean. 
  • javax.persistence.EmbeddedId – It is used to specify a composite primary key in the entity bean. 
  • javax.persistence.Column – It specifies the column name in the database table. 
  • javax.persistence.GeneratedValue – It defines the strategy needed for generating the primary key.


46) Which design patterns are used in Hibernate?

Hibernate uses the following Design patterns 
  • Domain Model Pattern -An object model of the domain that incorporates both behaviour and data. 
  • Proxy Pattern for lazy loading. 
  • Factory Pattern in Session Factory 


47) What is @Transient in Hibernate? 

If a variable is marked @Transient then it will not be added to the database. This means it has no persistence representation in that hibernate session. And after an application is closed these transient objects will be destroyed through garbage collection.

	@Transient
private String opt;


48) Which are the various collection types in Hibernate?

There are five distinct collection types that are used in hibernate for one-to-many relationship mappings. 

• Bag 
• Set 
• List 
• Array 
• Map


49) What is @Projections in Hibernate? 

The Projection class is used in Hibernate to query specific elements. It also provides some built-in aggregate functions like sum, max, min etc. The Projections class provides several static factory methods for obtaining Projection instances. After you get a Projection object, add it to your Criteria object with the setProjection() method.


50) Which one is faster JDBC or hibernate? 

JDBC will always give better performance as compared to Hibernate for most of the database vendors. The choice of hibernate over jdbc and sql queries is not because of the performance but because of reasons mainly object persistence and database independence in terms of not writing database specific queries.

Popular posts from this blog

Spring boot video streaming example-HTML5

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System

Java - Blowfish Encryption and decryption Example