Hibernate is one of the most popular ORM Tools used for Java applications. It’s widely used for performing database operations in enterprise applications.
In this Hibernate interview questions blog, we have collected the important Hibernate interview questions and answers from experts to help you get acquainted with the nature of questions you will encounter during your Hibernate interview.
Whether you’re a beginner or experienced, this Hyperion interview questions blog will definitely be helpful to take your Hibernate career to the next level in 2020.
Let’s get started.
Hibernate Interview Questions and Answers
Q1) What is Hibernate?
- Hibernate is anopen-source and lightweight ORM tool used for storing, manipulating, and retrieving data from the database.
- It is free software distributed under GNU Lesser General public license.
- It is also one of the most widely used ORM tools for java applications.
- Hibernate offers a reference implementation of the Java Persistence API, and that makes it an ideal choice as an ORM tool with advantages of loose coupling.
- The implementations include tasks like establishing a connection with the databases or writing a query for CRUDoperations, etc.
- Hibernate is mostly preferred for database operations in enterprise applications.
Q2) What is HQL (Hibernate Query Language)? And explain its advantages.
- Hibernate Query Language is also referred to as object-oriented query language and is database independent.
- It similarly considers java objects as SQL.
- It’s closer to object-oriented programming and is case insensitive excluding java class and variable names.
The main advantages of using HQL are listed below:
- Writing a query is simple.
- Database independent means if any program is written using HQL command then that program will be executable in all the databases without any changes.
- Supports object-oriented features like polymorphism, Inheritance, Associations, and more.
- For operations, application servers are not required.
- By using smart fetching strategies, database access can be minimized.
- Mapping of java classes to database tables are managed without writing any code.
Q3) What is ORM?
ORM stands for Object Relational Mapping. It is a programming strategy employed for mapping the object with the data stored in the database. It also helps in simplifying data creation, manipulation, and access. To interact with the databases, it internally uses Java API.
Q4) What are the advantages of Hibernate over JDBC?
The following are the major advantages of using Hibernate over JDBC:
- Hibernate code works great for every database, whereas JDBC is database specific.
- To work with Hibernate, no SQL knowledge is required as it is a set of objects, whereas, in JDBC, one needs to possess SQL knowledge.
- Hibernate Query Language is similar to object-oriented and close to JavaJava. But in JDBC, one needs to write SQL queries.
- In Hibernate, there is no need to write code for transaction management. But in JDBC, one needs to write code using rollback and commit for transaction management.
- Query tuning is automatic in Hibernate. By using criteria queries, the performance results are achieved at its best. But in JDBC, query tuning needs to be done by the database authors itself.
Q5) List ORM frameworks based on JavaJava.
Popular ORM frameworks based on JavaJava are listed below:
- Enterprise JavaBeans Entity Beans
- Java Data Objects
- Spring DAO
Q6) Name a few databases that are supported by Hibernate in JavaJava.
Hibernate supports various databases in Hibernate. Few of them are listed below :
- HSQL Database Engine
- Sybase SQL Server
- Informix Dynamic Server
- Microsoft SQL Server Database
Q7)What are the frameworks/java based tools that are supported by Hibernate?
Hibernate supports a variety of frameworks/java based tools like:
- XDoclet Spring
- Eclipse Plug-ins
Q8) Explain Hibernate architecture.
Hibernate architecture includes many interfaces like SessionFactory, Session, configuration, transaction, query, and criteria.
The Hibernate architecture is mainly categorized into four layers as.
- Java application layer
- Hibernate framework layer
- Backhand API layer
- Database layer
Q9) What are the key object/components of the Hibernate?
Following are the key objects/components of Hibernate:
- Session: Helps in getting a physical network with the database.
- Transaction: Denotes the unit of work with a database.
- Query: To retrieve the data from the database and create objects using SQL and HQL string.
- Criteria: Used for creating and executing object-oriented queries and retrieving the objects.
- Configuration: Represents the properties of files required by Hibernate
- Session Factory: Configures hibernate for the application with the provided configuration file and instantiates the session object.
Q10) What are the different types of associations available in Hibernate?
Four types of associations are available in Hibernate.
- One to One
- One to Many
- Many to One
- Many to Many
Q11) What is One-to-One association in Hibernate?
In simple terms, the One-to-One association is just similar to the Many-to-One association, but the difference is that the column will be set as unique. Consider, if two entities are there in One-to-One relationship, then one entity should have only one occurrence in the other entity.
Many-to-one elements are used for describing One-to-One association.
Q12) Explain One-to-Many association?
In simple terms, One-to-Many mapping means one object can be associated with multiple objects. It is executed through a Set Java collection, which does not have any redundant element.
Q13) What is Many-to-one mapping in a Hibernate?
This mapping is the most similar type of association where one object can be associated with multiple objects. Many-to-one elements are used to create the Many-to-One relationship entities.
Q14) Describe the Many-to-Many association.
Many-to-Many association in Hibernate indicates the relation between one entity to many other entities and column attribute for linking intermediate columns.
Many-to-Many mapping needs an entity attribute and a ManyToMany annotation. Either it can be unidirectional or bidirectional.e
For Unidirectional, the attribute models the association and can be used to navigate it in JPQL queries or domain models.
For bidirectional, mapping supports you to navigate in both directions.
Q15) What is Hibernate Configuration File?
Hibernate Configuration File (cfg file) is used for initiating SessionFactory and includes database-specific configuration. This file is used in Hibernate for establishing a connection to the database server. Hibernate.cfg.xml is the official name for this file.
Q16) Explain the Hibernate Mapping File.
Hibernate Mapping File is used for obtaining information regarding the mapping of a POJO class and a database table.
It mainly contains the mapping information of a POJO class name to a database table name and POJO class properties to database table columns.
Following are the elements of the Hibernate mapping file:
- hibernate-mapping: It is the root element.
- Class: It is used to map the POJO class to a database table.
- Id: Represents the unique key attribute or primary key of the table.
- generator: Used to generate id automatically.
- property: Describes the mapping of a POJO class property to the database table column.
Q17) How criteria object is different from the transaction object in Hibernate?
Criteria objects are used for creating and executing object-oriented queries for retrieving the objects, whereas transaction objects denote a unit of work with the database and most of the Relational Database Management System supports transaction functionality.
Q18) What is a Hibernate Query object?
- The Hibernate Query object is used for the purpose of retrieving data from the database. Either an SQL or Hibernate Query Language (HQL) can be used.
- A Query instance can be called using Session.createQuery().
- The Query object is used for binding query parameters, limiting query results, and executing the query.
The most frequently used Query methods are listed below:
Q19) What is Hibernate caching? And explain its types.
Caching is a mechanism used for improving the performance of a system. Hibernate caching queries data and achieves faster application performance.
Caching plays an important role in Hibernate and is designed to reduce unnecessary database access.
Hibernate provides mainly three types of caching.
This is used to cache objects within the current Session. By default, it’s enabled in Hibernate. Objects inside the session cache will stay inside in the same memory location.
2.Second Level Cache:
This is useful for caching objects across sessions. Objects will be searched in the cache,when this is enabled, and if not found, database query will be removed. It is an optional cache. And, mostly the first level cache will be consulted before any attempt is performed to locate an object in the second-level cache.
This is used for caching the results of a query. It’s useful for queries that often run with the same parameters.
Q20) Explain Hibernate Concurrency Strategies.
Concurrency strategies are mediators, responsible for storing and retrieving items of data from the cache. In case of enabling a second-level cache, we have to decide, for each persistent class and collection, which cache concurrency strategy to use.
Popular Concurrency strategies are listed below:
- Transactional : This strategy is used mostly to read data, where the prevention of stale data is critical in concurrent transactions.
- Nonstrict-read-write : This concurrency strategy is not used as a guarantee of consistency between the database and the cache.
- Read-write : This strategy is similar to transactional strategy.
- Read-only : This concurrency strategy is used for data that never changes. Mostly, it is preferred as reference data only.
Q21) Does Hibernate SessionFactory is thread-safe?
Yes, Hibernate SessionFactory is thread-safe as its internal state is immutable. Simultaneously, multiple threads can be accessed to get session instances.
Q22) Does Hibernate Session is thread-safe?
No, Hibernate session is not thread-safe. Every thread should get its own session instance and close it after work is finished.
Q23) What is the method used to create an HQL Query and SQL Query?
- For HQL query string, Session.createQuery is used to create a new instance of a query.
- For the SQL query string, Session.createSQLQuery is used to create a new instance of a query.
Q24) Describe the Hibernate Session.
Hibernate session is the core interface for performing database operations. It’s the interface between the Java application layer and Hibernates.
This Session offers methods to execute create, read, update and delete operations for a persistent object. Can also be used to execute SQL native queries, HQL queries, and create criteria using Session objects.
Q25) What do you mean by Lazy loading in Hibernate?
Actually, it’s a technique used for loading objects based on the requirement. Lazy loading is by default enabled from the release of Hibernate 3 version so that the child objects are not loaded while the parent is loaded.
Q26) What are the persistent classes in Hibernate?
Persistent classes in Hibernate are those whose objects and instances in the Java classes are stored in the database classes.
Q27) Explain Hibernate dialect?
Hibernate Dialect is used for specifying the database type. This one is required to generate appropriate SQL type statements based on the type of database.
Q28) How to write composite key mapping in hibernate?
In Hibernate, Composite key mapping is written in two ways, EmbeddedId and IdClass. The following rules must be followed for a primary key to be composite:
- The primary key must be public, and its properties should be public or protected.
- The primary key class must be serializable and must define hashCode and equals.
- The primary key class should also be defined to denote the composite primary key.
- If the primary key follows these rules, then it can be mapped with composite using IdClass or embedded.
Q29) Explain object states in Hibernate?
In Hibernate, there are three states of the object.
Transient: If an object is just created and has no primary key and is also not associated with the Session, then it is a transient state.
Persistent: If a session is opened and an instance is saved or retrieved from the database, then the object is in a persistent state.
Detached: If a session is closed, then the object is in a detached state. The object comes to a persistent state if you call lock() or update() method, after the detached state.
Q30) Name a few ways of inheritance mapping in Hibernate?
Mostly, there are three ways of inheritance mapping in hibernate.
- Table per concrete class
- Table per hierarchy
- Table per subclass
Q31) How can you make an immutable class in hibernate?
If you mark a class as mutable= “false”, then the class will be treated as an immutable class. By default, it is mutable=”true”
Q32) Will it be possible to perform collection mapping with One-to-One and Many-to-One?
No, it’s not possible. Collection mapping can only be performed with One-to-Many and Many-to-Many.
Q33) How is First level cache different from the second level cache?
The first level cache is associated with the Session and enabled by default, whereas Second level cache is associated with the SessionFactory and is not enabled by default.
Q34) Why should we use the Hibernate Session merge() call?
Hibernate merge is used for updating existing values. Hibernate Session merge() call is used for the purpose of creating a copy from the passed entity object and returning it. The passed entity is not tracked, and the returned entity is tracked for any changes.
Q35) List the collection types in Hibernate.
In Hibernate, five collection types are used for one-to-many relationship mappings.
Q36) What are the ways to implement joins in Hibernate?
There are many possible ways to implement joins in Hibernate.
- By using associations such as one-to-one, one-to-many etc.
- JOIN in the HQL query.
- By firing native sql queries and using join keywords.
Q37) Does native SQL query can be executed in hibernate?
Through the use of SQL Query objects, Hibernate provides an option to execute native SQL queries. It is, however, not the recommended approach for normal scenarios, because it loses the benefits related to hibernate first-level caching and hibernate association.
Q38) What is Named SQL Query? And explain its benefits.
In Hibernate, Named query is a technique used for grouping the HQL statements in a single location and lately referring them by some name whenever needed to use them. They are defined in Hibernate mapping files or through the use of JPA annotations @NamedNativeQuery and @NamedQuery.
Following are the benefits of Named SQL Query:
- Helps in grouping queries at a central location instead of letting them scattered all over the code.
- When the hibernate session factory is created, Hibernate Named Query syntax is checked to find any errors in the named queries.
- Once a Hibernate Named Query is defined, it can be used throughout the application.
Q39) What is cascading? And explain its types.
In general, when there is a relationship between the entities, then there is a need to define how different operations will affect the other entity. This is done using cascading.
Below listed are the cascading types supported by the Java Persistence Architecture
- CascadeType.PERSIST :
In this, save() or persist() operations cascade to related entities.
Related entities are merged in this type when the owning entity is merged.
If a “manual detach” occurs, then this detaches all related entities.
This removes all related entities associated with this setting when the owning entity is deleted.
It does the same thing for the refresh() operation.
For all the above cascade operations, this type is shorthand.
Q40) Explain the Hibernate Validator Framework?
JSR303 and JSR349 provide specifications for validating a bean by using annotations. Hibernate Validator presents the reference implementation of both these bean validation specs.
These are all about Hibernate interview questions and answers, I hope this is helpful for your interview as a recent or experienced person. If I miss any important questions, please let me know and I will add it to the list.