Hibernate Interview Questions for Revision

Hibernate is one of the most popular ORM tools in the market. It is one of the most complete Java framework in the market. Hibernate interview questions are usually easy to answer if you know all the basics.

 

This article covers the full theory behind Hibernate with relevant questions and their answers. Keep in mind that these are basic knowledge only and you must look at Hibernate online courses if you want to learn the most popular ORM tool in the market.


What is Hibernate? or What is an ORM?

(This answer below is correct for both)

Hibernate Interview Questions

Hibernate is an ORM (object relational mapping) tool.

 

It allows use to save objects into a Relational Database (RDBMS) system by converting objects into rows and fields into table headings.

 

The programmer provides information to Hibernate about which class corresponds to which table in the database. To save an object, simply call the appropriate method of Hibernate. The ORM tool (i.e. Hibernate) reads the mapping information to construct the SQL query and fires it on the database.

 

To read an object from database, the programmer calls Hibernate methods. The ORM executes SQL query, reads the data, uses the mapping information and packs the raw data into object(s) of the mapped class.

 

This way it we don’t need to manually pack / unpack objects to create SQL queries.

 

What are the advantages of Hibernate?

 

Hibernate Interview Questions

  • Hibernate is an open-source, database-independent ORM tool. If we change the database type from one vendor to another, we don’t need to change the code of the entire application. Through the use of “dialect” class from Hibernate library, Hibernate automatically adapts its queries to the type of database engine it is communicating with.

 

  • Hibernate provides automated query generation: In Hibernate, all basic database operations – CRUD operations – can be performed without writing queries. It provides Java methods corresponding to these operations which automatically create the queries automatically. However, complex operations may require use of HQL and native SQL queries.

 

  • HQL (Hibernate Query Language) enables object-oriented operations: HQL queries work on entity classes and their fields; you don’t need to know the details of the database to write a query.

 

  • Hibernate automatically tracks state of objects: Objects go through either transient, persistent, or detached states. If the object is in a persistent state, any changes to it are automatically inserted and committed to the database without writing any explicit method call or a query. At the end of each session, Hibernate checks the state of all persistent objects against their mapped database rows. If the data doesn’t match, Hibernate automatically fires an update query to copy the changes of the persistent object into the database.  This way developer is freed from the extra responsibility of keeping the database in a consistent state.

 

  • Hibernate is backward compatible as it supports JPA annotations. This means any old code written with JPA does not need major modifications when integrating it with Hibernate framework.

 

  • Hibernate is currently the most popular ORM tool in the market. It provides so many features including different ways to persist / retrieve an object. You can use native SQL queries, special HQL queries, or criteria queries (fully programmable and object-oriented) or even Hibernate’s own basic methods. It also support different object relationships (association, aggregation, etc). Due to the virtue of being the leader of ORM tools, it also enjoys massive support among the developer community. The documentation is really robust and developer community is vast and helpful.   

What is dialect in Hibernate?

 

Hibernate Interview Questions

SQL is a database communication standard, but it’s implementation is not uniform across all databases. There are changes in SQL implementation by different database vendors. Our clients may use different database, our product must work uniformly across all of them. If a client uses a database vendor which is different from the one we used during product development, our stock version of the application may not work with full accuracy on a different database. Adapting our database related code / queries across each different database is time-consuming and tedious. So, we need to code our application in order to minimize the “rework”. Hibernate allows us to do that with help of dialect class.

 

If we change the database type from one vendor to another, we don’t need to change the code of the entire application. Just select the appropriate dialect class from Hibernate library, and it will automatically adapt its queries to the type of database engine it is communicating with.  

 

In real world, most languages have various versions and flavors in different regions. Variations may be due to addition of new words or removal of words and different pronunciations. Similarly, a dialect in Hibernate corresponds to a variation of SQL which the base database will accept. Dialect conforms to a database; as database changes, the developers just need to select the corresponding dialect class.

 

How does Hibernate help overcome the disadvantages of JDBC?

 

  • Hibernate automatically maps objects to their corresponding rows in the database. With JDBC, every time you have to unpack an object to use it in an SQL query. While retrieving, you have to manually pack the data from the ResultSet into an object. This requires the developer to know both the database entity structure and the structure of its mapped class. Hibernate automates the object creation and gets rid of manual construction of objects so developer can focus on business logic.

 

  • With JDBC, everything related to connection has to be done manually – creating it, managing it, and closing it, as well as connection pooling. In Hibernate, the developer just has to open the session, perform transaction, and close it. All connection management operations are handled by the framework.

 

  • Because of this, a lot of boiler-plate code is reduced. (repetitive code with different parameters is called boiler-plate code).

 

  • With JDBC, we write raw SQL queries which have to manually changed all across the several modules of your application for every new vendor database. Because of the notion of dialect in HIbernate, the developer can be completely unaware of the database. The CRUD operations in Hibernate are performed on entity classes – not on database tables. The framework automatically generates the queries and dialect class of the database translates them into the SQL flavor suitable for the destination database. So whenever you change the database, simply change the dialect – no need to touch the code that performs the CRUD operations.

 

  • With JDBC, all the features of an RDBMS i.e. aggregation, inheritance, etc have to implemented manually by the developer. Hibernate provides all these features automatically. This saves a major part of time and efforts for the developer.

 

How do we provide ORM mapping in Hibernate?

 

Hibernate Interview Questions

Hibernate supports specification of object-to-relation mapping (ORM) in 2 ways:

 

1) Write hibernate mapping (HBM) files in XML where we will manually link each entity class with a database table and each field in the class with a column of that table. Here, each class has its own HBM files and therefore total number of files is higher.

 

2) Use JPA or Hibernate annotations to specify mapping within the entity class itself.

It reduces number of files and the developer need not know XML.

 

What is JPA and how is it related to Hibernate?

 

Hibernate Interview Questions

JPA stands for Java Persistence API. It is an ORM specification which provides a set of interfaces on how to implement various ORM functions. Hibernate is an open-source ORM tool which implements the JPA standard. As the user “johnm” puts it perfectly in this answer on stackoverflow, JPA is the dance, Hibernate is the dancer.

 

Toplink is similar to Hibernate; it is another “JPA Provider”. If you have learnt JPA before, then most likely you have used annotations from Toplink packages.

 

While this provides a good view of how JPA and Hibernate are related, it will be very naive to assume JPA came before Hibernate.

 

The truth is Hibernate was actually being developed independently in the ORM community before JPA was announced. So, ORM was a functionality which came into third-party frameworks first but was not a part of official JDK specification,

 

JCP (Java Community Process) is a group that interfaces with the open-source community and takes care of incorporating these requirements into the language as a formal standard. They worked closely with Hibernate and other ORM tool vendors to create a generic specification which does not depend on a particular vendor. As a result of efforts of the JCP, the formal release of JPA 1.0 was announced in 2006. As more features got added, JPA 2.0 came out in 2009.

 

[Reference: Answer by user “Ken Block” on the same stackoverflow question linked above]

 

What are the different ways to fetch objects using Hibernate?

 

Hibernate Interview Questions

There are many different ways to retrieve / persist objects with Hibernate.

  • Plain Hibernate methods like get(), save(), update(), merge(), etc. – For simple operations without queries

 

  • Queries in HQL (Hibernate query language) – For complex operations on the mapped entity classes, requires no knowledge of the database structure. But the developer has to be familiar with the HQL syntax and there is a slight learning curve. So, this is suitable for developers who are already familiar with SQL syntax but do not want to get into the details of the database structure.

 

  • Criteria Queries: Direct methods on objects, no need to create any query. Completely object-oriented and programmatic way of performing simple as well as complex CRUD operations. There is no learning curve for the developer.

 

  • Native SQL Queries: For programmers who can write flawlessly in standard SQL and prefer to rely on good, old-fashioned database queries. Here, the learners need to be aware of the fact that the Hibernate dialect still works. You have to writing in standard SQL, and the dialect translates it into vendor-specific SQL.

 

Explain the various object states in Hibernate.

 

Hibernate Interview Questions

A newly created object which is yet to be persisted (or attached to a session by any other method), it is said to be in TRANSIENT state.

 

When a transient object is attached to a session by any method, it is said to be in PERSISTENT state. Hibernate tracks the state of all objects in the persistent state. Any changes to these objects marks them as “dirty”. At the end of the session, Hibernate framework fires update operations to copy the state of all “dirty” persistent objects into the database. Thus, the developer doesn’t have to worry about keeping the database in a consistent state.

 

When the session is closed, all persistent objects move to DETACHED state and the framework stops tracking their changes.

 

Explain Hibernate Architecture and its important objects

 

Hibernate Interview Questions

Picture courtesy cloudsopedia.com

Hibernate works with your application to help manage database transactions over the low-level JDBC API. It is a comprehensive but light-weight framework.  It has a feature of “dialect” which automatically creates SQL queries suitable for your end-database. This way it provides abstraction to write database-independent calls without explicitly writing your own queries.

 

Hibernate’s Own Objects

 

Apart from the 3 main objects (Configuration, SessionFactory, Transaction), Hibernate has 3 additional objects (Session, Query, Criteria).

 

Configuration object

 

Application creates this object to read Hibernate configuration parameters such DB connection details, dialect, pooling information etc. To create this object, the developer can put the application config details in “hibernate.properties” (by default) or “hibernate.cfg.xml” file. This is an initialization-time only object (i.e. used only once).

It is used to create SessionFactory instance for the application.

 

SessionFactory object

 

Application uses this as a factory class to generate objects of type “Session”. Typically, an application will use a Configuration object to derive a single SessionFactory object. This SessionFactory instance will be shared by multiple threads each of which may request for new Session objects as desired.

 

The internal state of this object stores all the object-relational mapping information.

 

Therefore, it is important to take care of two things when using SessionFactory:

  • Make your SessionFactory instance a singleton because the creation of this object consumes a lot of resources. If you create many instances of SessionFactory, it will slow your application down. (Refer this link for Singleton Design Pattern)

 

  • Make sure objects using SessionFactory singleton are using it in a synchronized manner because it is a shared object.

 

Session object

 

This is the main object in a Hibernate application; it enables us to conduct operations on the database. Objects in Hibernate have 3 states transient, persistent, detached depending on their association with Session object

 

This object is extracted from the SessionFactory object as described earlier. It provides several methods to perform CRUD (Create, Retrieve, Update, Delete) operations on the database. As you call an appropriate method, Hibernate will generate SQL queries to be executed directly on the database. Hibernate also uses the dialect class selected in hibernate.cfg.xml to translate the base SQL queries and adapt them to the queries in the acceptable to the database.

 

Transaction object

 

There are often critical / complex update tasks for the database contain multiple update operations. It is necessary that all these operations a single task are executed completely. If anyone of the multiple operations fails due to any reason, changes done by all the previous operations in the task queue must be rolled back. It is important to maintain data integrity, without this structure the data is sure to get corrupted.

 

This functionality is provided through the use of “transactions”. Transaction objects are a part of a Session object. To start a transaction, call the beginTransaction() method. You can do read operations without transaction. But all write operations (i.e. Create, Update, Delete) operations need a transaction object. So first step to running a complex, multi-operation task is

  • extract the transaction object by using getTransaction() method on the Session object and store its reference in a variable.

 

  • call beginTransaction() method on the transaction object reference.

 

  • perform all operations using methods of Session object. Hibernate writes first any operations onto the Hibernate cache (not directly into the database).

 

  • call commit() method on the transaction object after all operations are completed. This call will flush all the write operations from Hibernate cache and save them permanently into the database.

 

This way we can use Transaction objects along with Session object in Hibernate to preserve data integrity.

 

Transaction object also provides secondary operations of Savepoint and Rollback. Savepoint is a point in a series of operations; it is literally like creating a bookmark. To mark the start of important series of operations, we will first create a “savepoint”. If during the execution of any operations if we get an error, we will use the “rollback” operation to undo all the changes done after the last created savepoint

 

Query and Criteria Objects

 

Using a session object, you can instruct Hibernate to generate only basic SQL queries. But large operations need sophisticated queries. We can use Query and Criteria objects to create and execute those queries on the database.

 

Hope you find this unique revision post with Hibernate Interview Questions useful.

Do share more Hibernate questions asked to you in your interview. I will do my best to answer them in the next article.

Leave a Reply