30+ Hibernate Interview Questions with Answers

In this article, we will discuss some important Hibernate framework interview questions and answers.
Let's begin with what is ORM?

1. What is ORM?

The term Object/Relational Mapping refers to the technique of mapping data from an object model representation to a relational data model representation (and vice versa).
For example, let's look at below diagram shows mapping between Student java model and database relational student table.

2. What is Hibernate Framework?

Hibernate is an Object/Relational Mapping solution for Java environments. Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is a java based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa.
Hibernate provides a reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use Hibernate persistence API for CRUD operations. Hibernate framework provides an option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration.

3. What is Java Persistence API (JPA)?

Java Persistence API (JPA) provides a specification for managing the relational data in applications.
JPA specifications are defined with annotations in a javax.persistence package. Using JPA annotation helps us in writing implementation independent code.

4. How does Hibernate relate to JDBC?

Hibernate uses JDBC for all database communications. Hibernate uses JDBC to interact with the database.

5. Explain Hibernate Architecture?

Hibernate, as an ORM solution, effectively "sits between" the Java application data access layer and the Relational Database, as can be seen in the diagram above. The Java application makes use of the Hibernate APIs to load, store, query, etc its domain data. Here we will introduce the essential Hibernate APIs.
As a JPA provider, Hibernate implements the Java Persistence API specifications and the association between JPA interfaces and Hibernate specific implementations can be visualized in the following diagram:

SessionFactory (org.hibernate.SessionFactory)

A thread-safe (and immutable) representation of the mapping of the application domain model to a database. Acts as a factory for org.hibernate.Session instances. The EntityManagerFactory is the JPA equivalent of a SessionFactory and basically, those two converge into the same SessionFactory implementation.
SessionFactory is very expensive to create, so, for any given database, the application should have only one associated SessionFactory. The SessionFactory maintains services that Hibernate uses across all Session(s) such as second level caches, connection pools, transaction system integrations, etc.

Session (org.hibernate.Session)

A single-threaded, short-lived object conceptually modeling a "Unit of Work". In JPA nomenclature, the Sessionis represented by an EntityManager.
Behind the scenes, the Hibernate Session wraps a JDBC java.sql.Connection and acts as a factory for org.hibernate.Transaction instances. It maintains a generally "repeatable read" persistence context (first level cache) of the application domain model.

Transaction (org.hibernate.Transaction)

A single-threaded, short-lived object used by the application to demarcate individual physical transaction boundaries. EntityTransaction is the JPA equivalent and both acts as an abstraction API to isolate the application from the underlying transaction system in use (JDBC or JTA).

6. What are the important benefits of using Hibernate Framework?

Some of the important benefits of using hibernate framework are:
  • Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
  • Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
  • Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, pol, morphism, and association.
  • Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because the learning curve is small and there are tons of online documentation and help is easily available in forums.
  • Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications.
  • Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it’s required.
  • Hibernate cache helps us in getting better performance.
  • For a database vendor specific feature, hibernate is suitable because we can also execute native SQL queries.
  • Overall hibernate is the best choice in the current market for ORM tool, it contains all the features that you will ever need in an ORM tool.

7. What are the advantages of Hibernate over JDBC?

Some of the important advantages of Hibernate framework over JDBC are:
  • Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks cleaner and readable.
  • Hibernate supports inheritance, associations, and collections. These features are not present with JDBC API.
  • Hibernate implicitly provides transaction management, in fact, most of the queries can’t be executed outside a transaction. In JDBC API, we need to write code for transaction management using commit and rollback. 
  • JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-catch block code. Most of the times it’s redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throw JDBCException or HibernateException un-checked exception, so we don’t need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.
  • Hibernate Query Language (HQL) is more object-oriented and close to a Java programming language. For JDBC, we need to write native SQL queries.
  • Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
  • Hibernate provides an option through which we can create database tables too, for JDBC tables must exist in the database.
  • Hibernate configuration helps us in using JDBC like connection as well as JNDI DataSource for a connection pool. This is a very important feature in enterprise application and completely missing in JDBC API.
  • Hibernate supports JPA annotations, so the code is independent of implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.

8. What is Hibernate Configuration File?

Hibernate configuration file includes the database specific configurations that are required to begin database connection using hibernate framework. The configuration file is usually an XML document with the name hibernate.cfg.xml. We provide database credentials or JNDI resource information in the hibernate configuration XML file. Some other important parts of hibernate configuration file are Dialect information, so that hibernate knows the database type and mapping file or class details.
Here is a sample hibernate.cfg.xml file:
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_db?useSSL=false</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="connection.pool_size">1</property>
        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- Echo the SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Set the current session context -->
        <property name="current_session_context_class">thread</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create-drop</property>
        <!-- dbcp connection pool configuration -->
        <property name="hibernate.dbcp.initialSize">5</property>
        <property name="hibernate.dbcp.maxTotal">20</property>
        <property name="hibernate.dbcp.maxIdle">10</property>
        <property name="hibernate.dbcp.minIdle">5</property>
        <property name="hibernate.dbcp.maxWaitMillis">-1</property>
        <mapping class="net.javaguides.hibernate.entity.Student" />
    </session-factory>
</hibernate-configuration>
Read more about Hibernate XML configuration file at http://www.javaguides.net/2018/11/hibernate-5-xml-configuration-example.html
In case you prefer to use Java-based configuration, check out more about hibernate Java-based configuration at http://www.javaguides.net/2018/11/hibernate-5-java-configuration-example.html

9. What are possible ways to configure object-table mapping?

There are two ways to map Java object to a relational table:
  1. Using XML based hibernate mapping
  2. Annotation-based hibernate mapping

10. What is Hibernate SessionFactory and How to Configure it?

SessionFactory is the factory class used to get the Session objects. SessionFactory is responsible to read the hibernate configuration parameters and connect to the database and provide Session objects. Usually, an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.
The SessionFactory maintains services that Hibernate uses across all Session(s) such as second level caches, connection pools, transaction system integrations, etc.
The internal state of SessionFactory is immutable, so it’s thread safe. Multiple threads can access it simultaneously to get Session instances.

11. Hibernate SessionFactory is a Thread Safe?

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

12. What is Hibernate Session and How to Get it?

A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
Behind the scenes, the Hibernate Session wraps a JDBC java.sql.Connection and acts as a factory for org.hibernate.Transaction instances. It maintains a generally "repeatable read" persistence context (first level cache) of the application domain model.

13. Hibernate Session is a Thread Safe?

Hibernate Session object is not thread safe, every thread should get its own session instance and close it after it’s work is finished.

14. What is the difference Between openSession and getCurrentSession?

Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file. Since this session object belongs to the hibernate context, we don’t need to close it. Once the session factory is closed, this session object gets closed.
<property name="hibernate.current_session_context_class">thread</property>
Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in a multi-threaded environment.
There is another method openStatelessSession() that returns stateless session, for more details with examples please read Hibernate openSession vs getCurrentSession.

15. Explain Hibernate Transaction Interface

In the hibernate framework, we have Transaction interface that defines the unit of work. It maintains abstraction from the transaction implementation (JTA, JDBC).

A transaction is associated with Session and instantiated by calling session.beginTransaction().

The methods of Transaction interface are as follows:
  • void begin() - starts a new transaction.
  • void commit()  - ends the unit of work unless we are in FlushMode.NEVER.
  • void rollback()  - forces this transaction to rollback.
  • void setTimeout(int seconds) - it sets a transaction timeout for any transaction started by a subsequent call to begin on this instance.
  • boolean isAlive()  - checks if the transaction is still alive.
  • void registerSynchronization(Synchronization s)  - registers a user synchronization callback for this transaction.
  • boolean wasCommited()  - checks if the transaction is committed successfully.
  • boolean wasRolledBack() - checks if the transaction is rolled back successfully.
Read more about Transaction interface at Hibernate API Java doc.

16. What is the Requirement for a Java Object to Become a Hibernate Entity Object? 

Let's discuss what are the rules or requirements to create a JPA entity class. An entity class must follow these requirements.
  • The class must be annotated with the javax.persistence.Entity annotation.
  • The class must have a public or protectedno-argument constructor. The class may have other constructors.
  • The class must not be declared final. No methods or persistent instance variables must be declared final.
  • If an entity instance is passed by value as a detached object, such as through a session bean's remote business interface, the class must implement the Serializable interface.
  • Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes.
  • Persistent instance variables must be declared private, protected, or package-private and can be accessed directly only by the entity class's methods. Clients must access the entity's state through accessor or business methods.
Read more about Hibernate/JPA entity at http://www.javaguides.net/2018/12/jpa-entity-class-basics.html

17. What is the Difference Between Hibernate Session get() and load() method?

  1. The key difference between the get() method and load() method is that load() method will throw an exception if an object with id passed to them is not found, but get() method will return null.
  2. The second important difference is that load() method can return proxy without hitting the database unless required (when you access any attribute other than id) but get() method always go to the database, so sometimes using load() method can be faster than the get() method.
Note: Use the load() method, if you know the object exists, and get() method if you are not sure about the object's existence.
Read more about the get() and load() methods at Hibernate 5 - get(), load() and byId() Method Examples

18. What is difference between Hibernate save(), saveOrUpdate() and persist() methods?

  1. Hibernate save() method can be used to save entity to the database. Problem with save() method is that it can be invoked without a transaction and if we have mapping entities, then only the primary object gets saved causing data inconsistencies. Also save returns the generated id immediately.
  2. Hibernate persist() method is similar to save() method with a transaction. It’s better to use persist() method than save() method because we can’t use it outside the boundary of a transaction, so all the object mappings are preserved. Also, persist() method doesn’t return the generated id immediately, so data persistence happens when needed.
  3. Hibernate saveOrUpdate() method results into an insert or update queries based on the provided data. If the data is present in the database, the update query is executed. We can use saveOrUpdate() without transaction also, but again you will face the issues with mapped objects not getting saved if a session is not flushed.

19. Why we should not Make an Entity Class final?

Hibernate use proxy classes for lazy loading of data, only when it’s needed. This is done by extending the entity bean, if the entity bean will be final then lazy loading will not be possible, hence low performance.

20. What is HQL and What are it’s Benefits?

Hibernate Query Language (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. HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform an action on a database. Although you can use SQL statements directly with Hibernate using Native SQL, I would recommend using HQL whenever possible to avoid database portability hassles and to take advantage of Hibernate's SQL generation and caching strategies.
Hibernate query language is case-insensitive except for java class and variable names.
The HQL queries are cached but we should avoid it as much as possible, otherwise, we will have to take care of associations. However, it’s a better choice than a native SQL query because of the Object-Oriented approach.

21. What is Named Query in Hibernate?


In Hibernate, a named query is a JPQL or SQL expression with a predefined unchangeable query string. You can define a named query either in hibernate mapping file or in an entity class.
Basically, named queries in hibernate is a technique to group the HQL statements in a single location, and lately refer them by some name whenever the need to use them. It helps largely in code cleanup because these HQL statements are no longer scattered in whole code.
Apart from the above, below are some minor advantages of named queries:
  1. Fail fast: Their syntax is checked when the session factory is created, making the application fail fast in case of an error.
  2. Reusable: They can be accessed and used from several places which increase re-usability.
Hibernate Named Queries can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery.

The following is an example of the definition of a named query in the JPQL/HQL:
    @NamedQuery(
            name="findAllCustomersWithName",
            query="SELECT c FROM Customer c WHERE c.name LIKE :custName"
    )
Hibernate provides support to create named queries using Native SQL. Here are @NamedNativeQuery and @NamedNativeQueries annotations to create named SQL query.


Read more about Named Query at http://www.javaguides.net/2018/11/hibernate-5-named-query-tutorial-with-examples.html.

22. What are the benefits of Named SQL Query?

Hibernate Named Query helps us in grouping queries at a central location rather than letting them scattered all over the code. 
Hibernate Named Query syntax is checked when the hibernate session factory is created, thus making the application fail fast in case of any error in the named queries. Hibernate Named Query is global, means once defined it can be used throughout the application.
However one of the major disadvantages of a Named query is that it’s hard to debug because we need to find out the location where it’s defined.

23. What is Cascading and What Are Different Types of Cascading?

Cascading is about persistence actions involving one object propagating to other objects via an association. Cascading can apply to a variety of Hibernate actions, and it is typically transitive. The "cascade=..." attribute of the annotation that defines the association says what actions should cascade for that association.

JPA allows you to propagate the state transition from a parent entity to a child. For this purpose, the JPA javax.persistence.CascadeType defines various cascade types:
  • ALL - cascades all entity state transitions
  • PERSIST - cascades the entity persist operation.
  • MERGE - cascades the entity merge operation.
  • REMOVE - cascades the entity remove operation.
  • REFRESH - cascades the entity refresh operation.
  • DETACH - cascades the entity detach operation.
Additionally, the CascadeType.ALL will propagate any Hibernate-specific operation, which is defined by the org.hibernate.annotations.CascadeType enum:
  • SAVE_UPDATE - cascades the entity saveOrUpdate operation.
  • REPLICATE - cascades the entity replicate operation.
  • LOCK - cascades the entity lock operation.
Cascading only makes sense only for Parent-Child associations (the Parent entity state transition being cascaded to its Child entities). Cascading from Child to Parent is not very useful and usually, it’s a mapping code smell.
The following examples will explain some of the aforementioned cascade operations using the following entities:
@Entity
public class Person {

    @Id
    private Long id;

    private String name;

    @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
    private List < Phone > phones = new ArrayList < > ();

    //Getters and setters are omitted for brevity

    public void addPhone(Phone phone) {
        this.phones.add(phone);
        phone.setOwner(this);
    }
}


@Entity
public class Phone {

    @Id
    private Long id;

    @Column(name = "`number`")
    private String number;

    @ManyToOne(fetch = FetchType.LAZY)
    private Person owner;

    //Getters and setters are omitted for brevity
}
Read more about cascading at http://www.javaguides.net/2018/11/guide-to-jpa-and-hibernate-cascade-types.html.

24. What are Design Patterns used in Hibernate framework?

Some of the design patterns used in Hibernate Framework are:
Read more in detail at https://ramesh-java-design-patterns.blogspot.com/2018/04/design-patterns-used-in-hibernate.html

25. What are different types of caches available in Hibernate?

Caching is a mechanism to enhance the performance of a system. It is a buffer memory that lies between the application and the database. Cache memory stores recently used data items in order to reduce the number of database hits as much as possible.
Hibernate provides 3 types of caching.
  1. Session Cache - The session cache caches objects within the current session. It is enabled by default in Hibernate. Objects in the session cache reside in the same memory location.
  2. Second Level Cache - The second level cache is responsible for caching objects across sessions. When this is turned on, objects will first be searched in the cache and if they are not found, a database query will be fired. The second level cache will be used when the objects are loaded using their primary key. This includes fetching of associations. Second level cache objects are constructed and reside in different memory locations. The second level cache is required to be configured with external cache provider like EhCache.
  1. Query Cache - Query Cache is used to cache the results of a query. When the query cache is turned on, the results of the query are stored against the combination query and parameters. Every time the query is fired the cache manager checks for the combination of parameters and query. If the results are found in the cache, they are returned, otherwise, a database transaction is initiated.

26. What are the Different States in Hibernate?

  1. transient - New objects created in Java program but not associated with any hibernate Session are said to be in the transient state.
  2. persistent - An object which is associated with a Hibernate session is called Persistent object. While an object which was earlier associated with Hibernate session but currently it's not associate is known as a detached object. You can call save() or persist() method to store those object into the database and bring them into the Persistent state.
  3. detached - You can re-attach a detached object to hibernate sessions by calling either update() or saveOrUpdate() method.

27. Name JPA Annotations?

Answer: All JPA Annotations: Mapping Annotations - A quick reference to all JPA mapping annotations.

28. Name Hibernate Annotations?

Answer:  All Hibernate Annotations: Mapping Annotations - A quick reference to all Hibernate mapping annotations.

29. Explain Hibernate/JPA primary key Primary Key Generation Strategies?

The JPA specification supports 4 different primary key generation strategies which generate the primary key values programmatically or use database features, like auto-incremented columns or sequences.

1. GenerationType.AUTO - The GenerationType.AUTO is the default generation type and lets the persistence provider choose the generation strategy.
2. GenerationType.IDENTITY - The GenerationType.IDENTITY is the easiest to use but not the best one from a performance point of view.
3. GenerationType.SEQUENCE - The GenerationType.SEQUENCE is to generate primary key values and uses a database sequence to generate unique values.
4. GenerationType.TABLE - The GenerationType.TABLE gets only rarely used nowadays. It simulates a sequence by storing and updating its current value in a database table which requires the use of pessimistic locks which put all transactions into a sequential order.

30. Which are the Different Types of Relationships Available in Hibernate Mapping?

There are three different types of relationships that can be implemented in hibernate. They are:
  1. One to One — It represents the one to one relationship between two tables. 
  2. One to Many/Many to One — It represents the one to many relationships between two tables. 
  3. Many to Many — It represents the many to many relationships between two tables.

31. What is the Difference Between JPA and Hibernate?

As you probably know that JPA is just a specification, meaning there is no implementation. You can annotate your classes as much as you would like with JPA annotations, however, without an implementation, nothing will happen. Think of JPA as the guidelines that must be followed or an interface, while Hibernate's JPA implementation is code that meets the API as defined by the JPA specification and provides the under the hood functionality.

In short, JPA is the interface while Hibernate is the implementation.


You can learn Hibernate framework from end-to-end at Hibernate ORM 5 Tutorials
You can learn Java Persistence API at Java Persistence API
v

Comments