Top Java Hibernate interview questions

In this article, I will be listing the frequently asked interview questions on hibernate in java application. These questions are collected from real interviews. All these questions check whether a candidate has basic knowledge of the hibernate.

orm

orm

1)  What’s ORM?

Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a library that implements the Object-Relational Mapping technique, hence the phrase “an ORM”.  There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to construct their own ORM tools. For Java Hibernate is well known ORM library.

2) What are the Pros and Cons of using ORM Libraries

Pros

  • As with most libraries, ORM saves a lot of time and effort.
  • And ORM libraries are well tested and used by many organisations which makes them more  stable than code written by own team
  • It saves programmers from writing code for transactions which can a cumbersome task
  • ORM libraries are available for different languages and hence the programmers can code in their own langauge like Hibernate for Java
  • ORM allows also the usagae of OOP concepts like data inheritance
  • You can change between ORM libraries without much effort
  • ORM libraries also have caching which can make data retrieval faster

Cons

  • ORM libraries need learning curve
  • Sometimes complex queries generated by ORM libraries are not efficient.

3) Describe benefits and drawbacks of Hibernate.

You can use all the above advantages and disadvantages for hibernate as well if you are asked this questions. We will list here hibernate specific benefits and drawbacks.

Benefits

  • Hibernate provides out-of-the-box implementations for caching, mapping flat data to object graphs, SQL rendering, etc.
  • Having a great community adds a lot of value to any framework and Hibernate has a large, established community. I consider this as a big plus. If you have an issue with hibernate your answer on stackoverflow will be answered very quickly.
  • Hibernate is also an implementation of the Java Persistence API (JPA) specification. As such, it can be easily used in any environment supporting JPA
  • Hibernate supports lazy initialization, numerous fetching strategies and optimistic locking with automatic versioning and time stamping.
  • Hibernate is well known for its excellent stability and quality, proven by the acceptance and use by tens of thousands of Java developers.
  • Hibernate is highly configurable and extensible.
  • Hibernate was designed to work in an application server cluster and deliver a highly scalable architecture.

Drawbacks

  • A lot of effort is required to learn Hibernate. So, not very easy to learn hibernate easily.
  • Hibernate has some performance issues when writing complicated joins. Hibernate may generate more queries than expected. This may degrade the performance.
  • Hibernate does not allow multiple inserts. To insert a list of Object save has to  have to be called in loop. which is not very efficient.
  • Hibernate usually deserialises data eagerly, unlike JDBC drivers, which tend to keep serialized data in a more raw format, internally.  This can make queries returning serliazed data very slow even if the application is not needing the serialized data but needs the other attributes.
  • Hibernate inheritance can be sometimes confusing.

4) Difference between Hibernate and JPA?

Java Persistence API (JPA) is just a specification. These are specifications of a generic Java Persistence API. The API is provided in the JDK as a set of interfaces so that any application depends only on these interfaces and doesn’t need to think about the implementation details. It makes the coupling between ORM implementation and application very loose. And in theory one can just plug any implementation library without even changing a single line of code.

Hibernate is one of the many frameworks that provides the implementation for JPA.  But Hibernate provides much more functionalities than JPA has specified. And these Hibernate specific functionalities can be used by applications. But once an application does that it becomes tightly coupled to Hibernate.

5) What’s new in latest versions of Hibernate?

For this your should refer to the Hibernate site to find out which is the latest version. Currently, Hibernate 5 is latest major release and here are the latest features

  1. New Bootstrap API
  2. Java 8 support
  3. Expanded AUTO id generation support
  4. Naming strategy split
  5. Attribute Converter support
  6. Better “bulk id table” support
  7. Transaction management
  8. Schema Tooling
  9. Typed Session API
  10. Improved OSGi support
  11. Improved Bytecode Enhancement capabilities
  12. Spatial/GIS support

You can look at this stackoverflow questions 

6) What’s lazy loading?

When a relationship is defined in Hibernate, a fetch type has to be defined on this relationship.  The fetch type decides whether or not to load all of the relationships of an object when the object is fetched.  The fetech type can be either EAGER or LAZY. With EAGER Hibernate will load all the relationships when the object is fetched. With LAZY Hibernate will load the relationships only when the relationship is need like calling the get on the relationship the first time. EAGER is slow but easy to code. LAZY needs more coding but is very efficient. You can find more information here

7) What’s N+1 problem?

Fetching an Object that has a relations with many objects(one to many). First get of the primary object generates the query for the primary object. They a fetch of each of relationship object generates one query. Let us look at a hospital that has many departments.

class Hospital {
    int Id;
    Department[] departments
}

A query for Hospital generates one query. And then a get on each department generates N queries. That is an N+1 problem.

The advantages of N+1 query is that the query has less complexity and can have better performance if the joined objects are not needed with the original Objects first get.

8) Describe some Hibernate annotations.

  • @Entity : Annotation for entity beans
  • @Table: Specify the database table for the entity
  • @Column : Map table column for the attribute
  • @Id : Make an attaribute the id of the entity
  • @GeneratedValue : Database autoincreaments the attribute value
  • @Version : Control version or cuncurrency. More details can be found here 
  • @OrderBy : Sort the data. This can be put on the relationship to get that relationship list sorted by an attribute.
  • @Transient : If you dont want a property of an entity to be stored to db use this ananotation
  • @Lob : Sometime large objects like some serialized objects need to be stored to db. Use @Lob for them

9) What’s Hibernate Session and SessionFactory?

SessionFactory creates Sessions. An application usually is configured to have a single SessionFactory.  SesssionFactory is thread-safe and hence can be shared by different threads. Second-level cache is always associated with SessionFactory object. This cache is available to the whole application rather than a particular session.

Session is created for one unit of work like a transaction. Session is used to get a connection with the database. Session object is created when an application needs to interact with the database. First level cache in hibernate is associated with Session object

10) States of entity beans.

An entity bean has following states:

1. Transient : An object that has been created but never associated with a Hibernate Session.

2. Persistent :  When an entity is associated with the database table row and is being managed by the current Persistence Context, it is said to be in Persistent stage.

3. Detached :  When an Object is not associated with a Hibernate Session anymore but was previously associated with one, it is said to be in Detached state. On closing the Persistence Context all managed entities by it become detached. A detached entity can be associated again by either Session.update() or merge using Session.merge()

11) Caching levels in Hibernate.

Hibernate has two caching levels:

  1. First Level Cache : The first level cache associates to session. Objects are cached within the current session. This cache is only available for the lifetime of that particular session. Once the session is closed the cache is also gone.
  2. Second Level Cache: Second level cache is associated with SessionFactory. So the second level cache is available to all the users of SessionFactory. Since SessionFactory is usually a singleton so this cache usually survives the whole application life-cycle. But there are configured rules that invalidate this cache. Here you can find more.

12) Transactions support in Hibernate.

Hibernate uses JDBC API for persistence. Hibernate provides an API to isolate applications from the plysical transaction system in use.  Hibernate Transaction Object can be retrieved from Session. Transaction allows begin, commit and rollback. Here is more info.

13)  Give an example of Transactional anti-pattern

A famous example is Session per operation. An application opens and closes a Session for each and every database call in a single thread. Database calls should be grouped together. Best is to replace this anti pattern with an accepted pattern Session-per-request pattern.

13) What’s optimistic locking?

Optimistic locking  is optimistic about multiple transactions completing  without affecting each other. It is basically an assumption that they would affect each other. So the transactions proceed without locking the data resource that the transactions affect. Before committing, to check that data is not corrupted, a check is done that no other transaction modified the data. If the data is modified by other transaction then the committing transaction is rolled back. In Hibernate versionning data can be used for optimistic locking. Hibernate provide @Version annotation for storing versioning information.
14) What is ACID?

ACID is a set of properties of database transactions:

Atomicity :  Each transaction has to either all or nothing. If any part of a transaction fails then whole of the transaction fails.

Consistency : A transaction brings a database from one valid state to another valid state.

Isolation :  The concurrent execution of transactions results in a system state that would be obtained if the transactions were executed sequentially.

Durability :  Once a transaction is committed, it will so even in case of a crash, power loss or errors in relational database.

15) What is database normalization.

Normalization is process to organize data  in tables and columns so as to reduce redundancy and improve data integrity. Here are more details.

16) How would you approach to optimization of a slow query?

Here are some of the things to think about when a query is slow.

  1. All the databases provide a tool to examine the execution plans of a query., we can use such to tool to see what a database is doing to optimize our query. Is it using an index or it is doing a table scan.
  2. we can look if there is looping in the query. Can we remove the loop and make it into one query
  3. Retrieving only required columns. I recently had to optimize a query that was retrieving a row that had a serialized object as one of the data column. But that serialized object was never used. And hibernate was very slow retrieving data from this table. By removing that column from the select statement, i could reduce the query execution time considerably.
  4. Indexes can make slow performing queries very fast. If the column on which the filter needs to be indexed. Execution plan tools can help here by showing which index was used for the query. Indexing is not always a solution and can lead to slower queries sometimes.
  5. Caching can be an option. If nothing helps then a cache in the application can reduce the calls to the database.

 

Like this post? Don’t forget to share it!