Top 25+ Hibernate Interview Questions & Answers [ JAVA TRICKS ] |ACTE
Hibernate Interview Questions and Answers

Top 25+ Hibernate Interview Questions & Answers [ JAVA TRICKS ]

Last updated on 04th Jul 2020, Blog, Interview Questions

About author

Sandeep (Sr Technical Manager )

He is Possessing 7+ Years Of Experience in Hibernate. His Passion lies in Developing Entrepreneurs & Activities. Also, Rendered his intelligence to the Enthusiastic JOB Seekers.

(5.0) | 16547 Ratings 2287

In the Java ecosystem, Hibernate is a popular open-source framework that offers a reliable and effective object-relational mapping (ORM) solution. With Hibernate, mapping Java objects to database tables and vice versa, the relationship between Java applications and relational databases is made simpler.One of the main advantages of Hibernate is its transparent persistence mechanism, which makes it possible to store, retrieve, and manipulate objects in the database without the need for explicit SQL statements. Because they can now concentrate on the business logic of their applications rather than handling complex database operations, developers can create more intuitive and efficient software.

1. What is ORM tool?


An Object Relational Mapping (ORM) tool helps to simplify data creation, manipulation, and access by internally using the Java API to interact with the databases. It’s the technique that maps objects stored in the database.

2. What does “lightweight” mean?


In the context of computers, “lightweight” describes the app, computer program, or device that doesn’t use the many system resources due to its small memory footprint (RAM) and a low CPU usage.

3. What are the advantages of Hibernate?


  • It’s lightweight and open source
  • It reduces the code length, removing boilerplate code, freeing up developers for other tasks
  • It strengthens a object-level relationship
  • It facilitates generation of independent database queries
Advantages of Hibernate

4. Why is Hibernate better than Java Database Connectivity ?


  • Hibernate code is a cleaner and more readable thanks to the elimination of a boiler-plate code, something found in JDBC
  • Unlike JDBC API, Hibernate supports the associations, collections, and inheritances
  • HQL (Hibernate Query Language) is closer to the Java and is more object-oriented

5. What is @Formula annotation in Hibernate?


The @Formula annotation in Hibernate is the powerful and flexible tool that allows the developers to define custom SQL expressions as part of entity mappings.

6. Name some databases that Hibernate supports.


  • DB2/NT
  • Front Base
  • HSQL Database Engine
  • Informix Dynamic Server
  • Microsoft SQL Server Database

7. What is HQL?


HQL stands for Hibernate Query Language, a powerful object-oriented language independent of databases. like SQL, except that it uses the objects instead of table names.

8. Name the four ORM levels in Hibernate.


  • Full Object Mapping
  • Light Object Mapping
  • Medium Object Mapping
  • Pure Relational

9. What is Session in Hibernate?


A Session in the Hibernate is a lightweight, non-thread-safe object representing a single unit of work with the database. It is used to perform the CRUD operations on persistent objects.

10. What is a Session Factory?


A SessionFactory in Hibernate is a heavyweight and thread-safe object used to create and manage the multiple sessions across an application.

11. What is a statement – session being a thread-safe object?


The statement is incorrect. A Session in Hibernate is the lightweight and non-thread-safe object and should not be shared across the multiple threads.

12. What is the difference between first-level cache and second-level cache?


  Criteria First-Level Cache Second-Level Cache

Cache at the session level, only usable during one Hibernate session

Shared application-level cache that is used by several sessions.
Lifetime Lifespanexists only while a single Hibernate session is in progress. persists until specifically removed or invalidated, spanning several sessions and transactions.
Management Supervisory Autonomously controlled by Hibernate Demands management and configuration that is explicit.

Concurrency offers a way to control multiple users’ access at once during a session.

Demands extra thought be given to managing concurrent access and possibly stale data.

13. What is the Hibernate Configuration File?


The Hibernate Configuration File (hibernate.cfg.xml) is XML file used to configure the basic settings of Hibernate, such as database URL, username, password, and dialect.

14. How do I create an immutable class in hibernate?


To create an immutable class in Hibernate, should mark all class properties as ‘final’ and provide the only getter methods for them without any setters.

15. Explain the concept behind Hibernate Inheritance Mapping?


Hibernate Inheritance Mapping is used to represent inheritance relationships between the classes in a relational database. It allows developers to map a single table to multiple classes using the techniques like table per class hierarchy, table per subclass, and a table per concrete class.

16. Is hibernate prone to SQL injection attacks?


Hibernate, by itself, is not prone to SQL injection attacks. However, applications may be vulnerable to SQL injection attacks if user input is concatenated with the HQL or a Criteria queries.

17. Name the Hibernate’s five collection types used in one-to-many relationship mappings


The five collection types are:

  • Array
  • Bag
  • List
  • Map
  • Set

18. What is “dirty checking”?


The dirty checking feature helps the developers and users avoid time-consuming write actions, thereby reducing database write times. Dirty checking changes or updates only fields that require action, while keeping the rest of fields untouched and unchanged.

19. What is Hibernate’s default cache service?


Hibernate’s default cache service is the EHCache, though framework additionally supports:

  • OSCache
  • SWARMCache
  • TreeCache

20. What is Light Object Mapping?


Light Object Mapping is one of the more valuable levels of ORM quality. This approach uses the specific design patterns to hide syntax from business logic.

    Subscribe For Free Demo


    21. List the Hibernate framework’s essential interfaces.


    SessionFactory:SessionFactory is an immutable thread-safe cache of the compiled mappings meant for a single database.

    Session: A session is a single-threaded, short-lived object that represents the dialogue between the persistent store and the application.

    Transaction: The transaction is a single-threaded, short-lived object that the application uses to specify the atomic units of work.

    22. What is lazy loading?


    Lazy loading is the technique where objects are loaded as to be needed, instead of an entire page, for example. This technique became a default since Hibernate version 3.

    23. What are concurrency strategies?


    Concurrency strategies are the mediators responsible for storing and retrieving cached items. When enabling the second-level cache, the developer must decide which cache concurrency to implement for each persistent class and collection.

    24. Define Hibernate’s validator framework.


    Data validation is the integral part of any application and is used in the presentation layer when using JavaScript and server-side code before a processing.

    25. Explain hibernate mapping file?


    A hibernate mapping file is the XML file that defines the relationship between the Java class and a database table.

    26. What are commonly used annotations available to support hibernate mapping?


    The most commonly used annotations for the hibernate mapping are:

    • Entity
    • Table
    • Column
    • Id
    • GeneratedValue
    • ManyToOne

    27. Explain Hibernate architecture


    Hibernate architecture consists of several components, such as Session Factory, Session, Transaction, and Query. For example, Session Factory is responsible for creating and managing sessions.

    28. What is the difference between getCurrentSession and openSession methods?


    The getCurrentSession method creates or retrieves a current Session from a current session context.In contrast, the open Session process begins the new session that is not bound to a current context.

    29. Differentiate between save() and saveOrUpdate() methods in hibernate Session ?


    The save() method is used to persist the new object in the database. In contrast, saveOrUpdate() method is used to continue the new object or update an existing object in the database.

    30. What distinguishes the Hibernate session’s get() and load() methods?


    The get() method retrieves the object from the database by its primary key and throws an exception if the object is not found. The load() method is also used to retrieve an object from a database by its primary key, but it returns the proxy object if it is not found.

    Course Curriculum

    Get On-Demand Hibernate Course to Enhance Your Career

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

    31. What are criteria for API in hibernate?


    The criteria API in hibernate is the programmatic way of creating and executing queries.

    32. What about one too many associations and how can I use them in Hibernate?


    A one-to-many association occurs when one entity is associated with multiple other entities.

    33. What are Many to Many associations?


    A many-to-many association occurs when the multiple entities are associated with the various other entities.

    34. What does Session.lock() method in hibernate do?


    The SessionSession.lock() method is used to acquire a lock on an object in a current Session. This is useful for preventing the concurrent updates to the same thing.

    35. What is hibernate caching?


    Hibernate caching refers to storing data in memory to retrieve it quickly without hitting the database again. This improves the performance and reduces the load on the database.

    36. What are Types of Hibernate Caching?


    There are the two types of hibernate caching first-level caching and second-level caching. First-level caching is enabled by a default and is associated with the Session object.

    37. When is the merge() method of hibernate Session useful?


    The merge() method of a hibernate Session is useful when needed to update an existing object in the database without reattaching it to the Session.

    38. Can Collection mapping be done using One-to-One and Many-to-One Associations?


    Yes, collection mapping can be done using the both One-to-One and Many-to-One associations.One-to-One association is used when a one object is associated with one other object.

    39. Difference between setMaxResults() and setFetchSize() of Query?


    The setMaxResults() method limits a number of results returned by a query, while setFetchSize() method controls the number of rows retrieved from the database at a time.

    40. Does Hibernate support Native SQL Queries?


    Yes, Hibernate supports the Native SQL Queries, which allow you to use SQL statements directly to interact with the database. This can be useful when you want to perform complex queries that are impossible with the HQL or Criteria API.

    41. What design patterns does the Hibernate framework use?


    • Data Mapper is a tool that transfers data between objects and databases while maintaining their independence from one another
    • Domain Model Pattern, which is domain object model that incorporates the both behaviour and data
    • Proxy Pattern, for a lazy loading
    • Factory pattern in the SessionFactory

    42. What is Hibernate tuning?


    The process of the Hibernate tuning is designed to optimise Hibernate applications’ performance. The three strategies are:

    • SQL Optimization
    • Session Management
    • Data Caching

    43. Name the states that a persistent entity exists in?


    Persistent entities exist in only a three states:

    • Transient
    • Persistent
    • Detached

    44. How can I view the Hibernate-generated SQL on the console?


    To enable the viewing SQL on console for debugging purposes, must add the following in Hibernate configuration file: 1 true

    45. What is the difference between Session and SessionFactory?


    A Session provides a first-level cache and is a single-threaded, short-lived object. A SessionFactory provides a second-level cache and is immutable and shared by all Sessions.

    46. How many ways can objects be fetched from Hibernate’s database?


    There are four ways to fetch objects from a Hibernate’s database:

    • Criteria API
    • HQL
    • The identifier
    • Standard SQL

    47. How many ways can disable Hibernate’s second-level cache?


    There are the three ways to disable the cache:

    • By setting hibernate. cache. use_second_level_cache property to false
    • By using the CACHEMODE.IGNORE
    • Using the cache provider such as org.hibernate.cache.NoCacheProvider

    48. Describe differences between Hibernate’s transient, persistent, and detached states?


    Transient: This state describes the new objects that are created in Java but not associated with the Hibernate session.

    Persistent: This state describes the objects associated with the Hibernate session.

    Detached: This state describes the object that was formerly Persistent and associated with the Hibernate session.

    49. What happens when no-args constructor is absent in Entity bean?


    If no-args constructor is absent in Entity bean, Hibernate cannot instantiate objects and throw an exception.

    50. Can declare the Entity class final?


    No, the Entity class cannot be a declared final, as Hibernate uses the runtime proxies to enhance the class for a persistence.

    Course Curriculum

    Best JOB Oriented Hibernate Certification Course from Real-Time Experts

    Weekday / Weekend BatchesSee Batch Details

    51. Explain Query Cache?


    The Query Cache is the second-level cache that stores the results of a query so that they can be reused later. It improves the performance by avoiding multiple times hitting the database for the same Query.

    52. What is the N+1 SELECT problem in Hibernate?


    The N+1 SELECT problem in Hibernate refers to a single SELECT statement being executed to retrieve a parent object. Then N SELECT statements are executed to retrieve child objects, resulting in the poor performance.

    53. How to solve the N+1 SELECT problem in Hibernate?


    The N+1 SELECT problem can be solved using the fetching strategies are eager loading, lazy loading, or batch fetching. Another solution is to use the JOIN FETCH clause in HQL or JPQL Query.

    54. What is a Single Table Strategy?


    The Single Table Strategy maps the multiple classes that inherit from a single root class to a single table in a database. Each row in the table represents an instance of one of the classes in hierarchy.

    55. Explain Table Per Class Strategy


    The Table Per Class Strategy maps the classes in an inheritance hierarchy to separate tables in the database. Each class in the hierarchy has its table, and the data for that class is stored in the corresponding table.

    56. What is named SQL Query?


    Named SQL Query is the feature in Hibernate that allows users to define a named query and reuse it throughout the application. It is defined in the mapping file or by using @NamedQuery annotation.

    57. What are the benefits of NamedQuery?


    The benefits of a NamedQuery include following:

    • Improved code maintainability and readability
    • Reduced the code duplication
    • Ability to easily change Query without affecting its code

    58. What features are supported by the Hibernate framework?


    • Lightweight
    • Open Source
    • Object Relational Mapping
    • High performance
    • Hibernate Query Languageg
    • Caching

    59. List the technologies supported by Hibernate.


    • XDoclet Spring
    • J2EE
    • Eclipse Plug-ins
    • Maven

    60. List interfaces supported by Hibernate framework.


    • ServiceRegistry
    • SessionFactory
    • Session
    • Transaction
    • Query

    61. Describe Hibernate collections types.


    Collection in hibernate is the list of unordered objects that may have duplicates. It is similar to the java.util.List, The simple collection type in hibernate is .

    62. List various collection types used in Hibernate.


    • ArrayType
    • BagType
    • CustomCollectionType
    • IdentifierBagType
    • ListType
    • MapType

    63. Describe Hibernate Template Class.


    The HibernateTemplate class helps with the different methods for retrieving and querying data from databases.

    64. List benefits of using HibernateTemplate.


    • Provides different methods for querying/retrieving data from the database.
    • Simplified interactions with the Hibernate Session.
    • Common functions are simplified to single method calls.
    • Exceptions are caught and converted to the runtime exceptions.

    65. List the strategies applied for performance tuning of hibernating applications.


    • SQL optimization
    • Session Management
    • Data Caching

    66. How does Hibernate Proxy support lazy loading?


    An uninitialized proxy from a desired entity class is created when Session.load() is called. These proxies or byte code enhancements are used to implement JPA lazy loading functionality.

    67. List the best practice for Persistent classes recommended by Hibernate.


    • hasCode() and equals() methods should be implemented.
    • Prevent using the references to ID in equals() method of the persistent class.
    • equals() and hasCode() methods should be accessed using a getter and setter methods.
    • The collection should not be mapped using Array.

    68. List different types of cascading.


    The various types of a cascading used by a Java Persistence API (JPA) and Hibernate are listed below:

    Java Persistence API Cascade Types

    • MERGE
    • REMOVE

    Hibernate Cascade Types

    • LOCK

    69. List the steps of integrating log4j logging with Hibernate.


    Log4j logging using xml file

    • Add a log4j and slf4j JAR files
    • Log4j.xml file creation in a src folder (along with hibernate.cfg.xml file)

    Logging using the log4j properties file

    • Add a log4j and slf4j JAR file
    • Create a log4j properties file that has a file path for a log file messages, console log message, root Logger options, and JDBC parameters for log.

    70. What are the advantages of the Hibernate Tools Eclipse plugin


    • Ease of testing, prototyping, and creation of the hibernate or JPA mapped projects.
    • Useful for exploring mappings, running queries, and generating code for data projects.
    • Support for the hibernating annotations, core hbm.xml, and JPA persistence projects.
    Java Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    71. List various joins that can be used in hibernate.


    There are the multiple ways can use joins in hibernate:

    • Joins in HQL.
    • Joins in SQL native query.
    • One-to-one, One-to-many, and many-to-many relations are used.

    72. List the ways objects can be retrieved from the Hibernate database.


    Objects can be retrieved from a Hibernate database in four ways:

    • Standard SQL
    • HQL
    • Criteria API
    • The identifier

    73. How to complete a transaction in Hibernate?


    There are the two distinct actions if looking to complete a transaction in hibernate:

    • Commit
    • Rollback

    74. Explain the difference between hibernate and Spring.


    While Hibernate is an ORM framework tool used for data persistence, Spring, on other hand, is a framework for enterprise applications. Moreover, Spring supports Hibernate and provides different classes which are essentially templates containing a common code.

    75. What is the difference between Hibernate save() and persist() methods?


    When a call persists on any existing object, it transitions from a transient to persistent state. However, it is not saved in the database. When calling the save method, the existing object is immediately saved in a database and returned.

    76. What is Hibernate Criteria API?


    The Hibernate Criteria API provides the easy and programmatic way to build queries in a Hibernate. It allows the developers to create queries using a smooth interface and includes the security.

    77. Explain the concept of Hibernate Envers.


    Hibernate Envers is an auditing framework that allows the developers to track entity changes over time. This feature is handy when facing debugging issues in a project.

    78. How do I optimise Hibernate queries to improve performance?


    • Use lazy Loading to reduce data retrieved from the database at once.
    • Use caching to reduce the number of database queries required.
    • Use batch fetching to retrieve the multiple entities in a single query.

    79. What is Hibernate proxy?


    Hibernate allows classes to be mapped as proxies instead of tables. When load in a session is called, a proxy may be returned. The methods to load data are included in the proxy.

    80. Explain Hibernate callback interfaces?


    Hibernate employs callback interfaces to collect event notifications from its objects. An illustration of this is that events are created when objects are loaded and deleted, and callback .

    81. What is a session interface?


    A session interface represents the hibernate session that performs a manipulation of database entities.

    82. Explain the “version field”.


    In case, offline information, backed by a database, is being changed, then data integrity at application level is highly important. A versioning protocol which is an advanced level of the locking, is needed to support it.

    83. Explain the role of addDirectory() and addjar() methods?


    The addDirectory() and addjar() methods in Hibernate allow users to load Hibernate documents. Both addDirectory() and addjar() methods play a significant role in simplifying the range of processes, such as layout, refactoring, configuration, and many more.

    84. What is Hibernate tuning?


    Optimising the performance of Hibernate applications is known as aHibernate tuning. Hibernate tuning is typically performed by employing data caching, session management, and SQL optimization.

    85. How does Hibernate accomplish database independence?


    Hibernate achieves database independence through its Object-Relational Mapping (ORM) framework. It abstracts SQL level details, allowing developers to interact with databases using the Java objects instead of writing SQL queries.

    86. How Hibernate handles ACID transactions?


    Hibernate manages the ACID transactions through its Transaction API. It ensures an Atomicity by treating each operation as a single unit, either fully completing or not at all.

    87. Difference between eager loading and lazy loading.


    Eager loading: eager loading involves the fetching not only the main data needed but also related or associated data upfront in a single query.

    88. What is the composite key in Hibernate?


    A composite key consists of the multiple columns that together uniquely identify a record in the table.Hibernate allows you to define and then use composite keys.

    89. How can I perform pagination using Hibernate?


    Pagination can be achieved using the setFirstResult() and setMaxResults() methods in the Hibernate queries, which limit the number of results returned.

    90. What is the use of the inverse attribute in Hibernate?


    The inverse attribute is used to optimise bidirectional associations. Setting it to true on one side of the relationship means that Hibernate will update the foreign key from that side.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free