Hibernate Interview Questions
- 18th May, 2021
- 777 Followers
Latest Interview Questions
Pratice HR Questions
Hibernate is a very popular ORM (Object Relational Mapping) offering from the Java/J2EE open source community. It's already being used widely in enterprise level applications by many software development companies. Our Hibernate Trainers have many years of real time industry experience aE" hence they are very much aware of the industry needs & will train you so that you fit exactly to real time industry requirements. Hibernate not only takes care of the mapping from Java classes to database tables but also provides data query and recovery facilities. Hibernate framework simplifies the development of java application to interrelate with the database. Hibernate is an open source, lightweight, ORM tool. Hibernate has its own internal connection pooling but it also support some third party connection pooling for manufacture use.
Hibernate Interview Questions
1) What is Hibernate?
Hibernate is a Java framework that simplifies the development of Java application to interact with the database. It is an open-source, lightweight, ORM (Object Relational Mapping) tool. Hibernate implements the specifications of JPA (Java Persistence API) for data persistence.
2) What is ORM?
ORM (Object-relational mapping) in computer science is a programming technique for converting data between incompatible type systems using object-oriented programming languages.
3) Enlist major advantages of Hibernate?
Major advantages of using Hibernate framework are
- Open-source and Lightweight
- Object-relational mapping
- Transparent Persistence
- Database independent
- Dual-layer Caching
- Supports JPA annotations
- Connection pooling
4) Why is Hibernate is preferred over JDBC?
Reasons to prefer Hibernate over JDBC
- It allows business code to access to the objects rather than Database tables.
- It hides the details of SQL queries from OO logic.
- It is based on JDBC "underhood".
- Dealing with database implementation is not required.
- Entities are based on business concepts rather than database structures.
- It generates automatic key and Transaction management.
- Application development is faster.
5) What are Key components of Hibernate?
Some core components of Hibernate are
- hbm.xml or Annotation
- Query Builder
6) What is Session object in Hibernate?
Session object in Hibernate 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.
7) What is HQL?
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 action on database.
8) What is Transaction in Hibernate?
Transaction in Hibernate is an interface available in org.hibernate package which is associated with the session. It is a sequence of operation which works as an atomic unit and maintains abstraction from the transaction implementation (JTA, JDBC). A transaction in hibernate is instantiated by the calling session.beginTransaction() method.
9) What is HCQL in Hibernate?
The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on the specific criteria. The Criteria interface provides methods to apply criteria such as retrieving all the records of a table whose salary is greater than 50000 etc
10) Enlist major databases supported by Hibernate?
Below is the list of major supported databases in Hibernate
- HSQL Database Engine
- Sybase SQL Server
- Informix Dynamic Server
- Microsoft SQL Server Database
11) What are the benefits of Named SQL Query?
Few benefits of Named SQL Query in Hibernate are
- 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, which means once defined it can be used throughout the application.
12) What are persistent classes?
Java classes whose objects or instances will be stored in database tables are called persistent classes in Hibernate. Hibernate works best if these classes follow some simple rules, also known as the Plain Old Java Object (POJO) programming model. All Java classes that will be persisted need a default constructor.
13) What is Query object in Hibernate?
The Hibernate Query object is used to retrieve data from the database. You can use either SQL or Hibernate Query Language (HQL). A Query instance is obtained by calling Session.createQuery(). The Query object is used to bind query parameters, limit query results and execute the query.
14) What is Hibernate caching?
Caching is a mechanism to enhance the performance of a system. It is a buffer memory that lies between the application and the database. Hibernate uses caching for improving the performance of the application by pooling the object in the cache. There are two types of caching mainly supported by Hibernate i.e First Level Cache, and Second Level Cache.
15) What is first level cache in Hibernate?
Hibernate first level cache is associated with the Session object. This cache is enabled by default and there is no way to disable it. However, hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely.
Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.
16) What is second level cache in Hibernate?
Hibernate provides another application level cache, known as second level cache, which can be shared among multiple sessions. It is useful if you have multiple session objects from a session factory. SessionFactory holds the second level cache data. It is global for all the session objects and not enabled by default.
17) What is Query level cache in Hibernate?
Query level cache in Hibernate is used to implement cache for query resultsets that integrates closely with the second-level cache.This is an optional feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated. This is only useful for queries that are run frequently with the same parameters.
18) Enlist different types of association supported by Hibernate?
Hibernate supports four types of association mapping. They are
- One to One
- One to Many
- Many to One
- Many to Many
19) What are concurrency strategies?
A concurrency strategy is a mediator, which is responsible for storing items of data in the cache and retrieving them from the cache. If you are going to enable a second-level cache, you will have to decide, for each persistent class and collection, which cache concurrency strategy to use.
20) What is Lazy loading in Hibernate ?
Lazy loading in hibernate is used to improve the performance of the application. It loads the child objects on demand. Since Hibernate 3, lazy loading is enabled by default, you don't need to do lazy="true". It means not to load the child objects when a parent is loaded.
21) Explain some applications of hbm.xml file in Hibernate?
Applications of hbm.xml file in Hibernate are
- It is used to define specific mappings from Java classes to database tables.
- It is used to define the mapping of unique ID attribute in class to the primary key of the database table.
- It is used to generate the primary key values automatically.
- It is used to map a Java class property to a column in the database table.
- It is used to map a java.util.set, java.util.Sortedset property in hibernate.
- It is used to map a java.util.List property in hibernate.
- It is used to map a java.util.Collection property in hibernate.
- It is used to map a java.util.Map property in hibernate.
22) Enlist important interfaces of Hibernate framework?
Hibernate supports five core interfaces. These interfaces are can be used to store and retrieve persistent objects and control transactions.
- Configuration interface
- Transaction interface
- SessionFactory interface
- Session interface
- Query and Criteria interfaces
23) What is a dialect in Hibernate?
Hibernate supports different database servers. Dialect in Hibernate specifies the type of database used in hibernate so that it generates appropriate type of SQL statements.
SQL Dialect Syntax
<property name="dialect">org.hibernate.dialect.Oracle9Dialect </property>
org.hibernate.dialect.Oracle9iDialect, org.hibernate.dialect.SQLServerDialect, org.hibernate.dialect.PostgreSQLDialect, org.hibernate.dialect.IngresDialect are few dialects in Hibernate.
24) What is Java Persistence API?
Java Persistence API (JPA) is a way for an application to persist and retrieve information from a non-volatile storage system. It is a Java application programming interface specification that describes the management of relational data in applications using Java Platform, Standard Edition and Java Platform, Enterprise Edition/Jakarta EE.
25) What is difference between save and persist in Hibernate?
Save() and persist() both methods are used for saving an object in the database.
|It returns generated id and return type is serializable||It does not return anything. Its void return type.|
|It can save an object within boundaries and outside boundaries.||It can only save object within the transaction boundaries.|
|It will create a new row in the table for a detached object.||It will throw persistence exception for detached object|
|It is only supported by Hibernate.||It is also supported by JPA.|
26) What is the use of @entity annotation?
The @Entity annotation specifies that the class is an entity and is mapped to a database table.
27) What is transient state object in Hibernate?
An object that is created for the first time using the new() operator is in transient state. When the object is in transient sate then it will not contain any identifier (primary key value). You have to use save, persist or saveOrUpdate methods to persist the transient object.
28) What is SessionFactory?
SessionFactory in Hibernate is an interface that can be created by providing the Configuration object, which will contain all DB related property details pulled from either hibernate.cfg.xml file or hibernate.properties file. SessionFactory is a factory for Session objects.
29) What is the difference between Hibernate get and load method?
In hibernate, get() and load() are two methods which is used to fetch data for the given identifier. They both belong to Hibernate session class. Get() method return null, If no row is available in the session cache or the database for the given identifier whereas load() method throws object not found exception.
30) What are different states of the Hibernate object?
Object states in Hibernate plays a vital role in the execution of code in an application. Hibernate has provided three different states for an object of a POJO class. These three states are also called as life cycle states of an object.
Below are three types of Hibernate object states
- Transient Object State
- Persistent Object State
- Detached Object State
31) What is dirty checking in hibernate?
Dirty Checking is one of the important features of Hibernate. In dirty checking, hibernate automatically detects whether an object is modified (or) not and needs to be updated. It saves the developer's time and effort in updating the database when states of objects are modified inside a transaction.
32) What are different states of an entity bean?
The Entity bean has three states:
- Transient: Whenever we create a new object of Entity bean then we can say that is in Transient state, At that time any modification in the object state does not affect on the database.
- Persistent: Whenever the Object of entity bean associated with the session we can say that is in persistent state, if any change in the object state, then that modification effects in the database.
- Detached: Whenever the object is removed from the session then it enters into detached state. Any modification on the detached state object does not affect in database.
33) How to implement Joins in Hibernate?
Different ways to implement Joins in Hibernate
- Using associations such as one-to-one, one-to-many,
- Using JOIN in the HQL query,
- and by using native sql query with join keyword.
34) What is cascading? Explain its types?
Cascading is a convenient feature to save the lines of code needed to manage the state of the other side manually. The cascade types supported by the Java Persistence Architecture are as below:
- CascadeType.PERSIST: cascade type
presistmeans that save() or persist() operations cascade to related entities.
- CascadeType.MERGE: cascade type
mergemeans that related entities are merged when the owning entity is merged.
- CascadeType.REFRESH: cascade type
refreshdoes the same thing for the refresh() operation.
- CascadeType.REMOVE: cascade type
removeremoves all related entities association with this setting when the owning entity is deleted.
- CascadeType.DETACH: cascade type
detachdetaches all related entities if a “manual detach” occurs.
- CascadeType.ALL: cascade type
allis shorthand for all of the above cascade operations.
35) What is Hibernate Validator Framework?
Hibernate validator can be used to validate data, which is a very important issue in every layer of an application. It provides set of annotations, that can be used to validate input fields of a form against constraints.
36) What are Collection types in Hibernate?
A collection in Hibernate is defined as a one-to-many reference. The simplest collection type in Hibernate is <bag>
ArrayType, BagType, IdentifierBagType, ListType, MapType, SetType are some collection types available in Hibernate framework.
37) What is hibernate bag collection?
A Bag is a java collection that stores elements without caring about the sequencing, but allow duplicate elements in the list. A bag is a random grouping of the objects in the list. A Collection is mapped with an <bag> element in the mapping table and initialized with java.
38) Explain Hibernate Template class?
HibernateTemplate Class is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.
39) What do you understand by Light Object Mapping?
Light Object Mapping is a level of ORM where classes represent entities and are manually mapped.
40) What is Evict in hibernate?
evict() is a method of Hibernate Session class that is used to detach an object from the session cache. Before using evict() the object must be present in the session cache.
Evict accept the object which is already synched with the session.
41) What is a proxy in hibernate?
A proxy is a subclass in Hibernate that are implemented at runtime. Hibernate creates a proxy (a subclass of the class being fetched) instead of querying the database directly, and this proxy will load the "real" object from the database whenever one of its methods is called.
42) What is hibernate configuration file?
Hibernate Configuration File(cfg file) is the file loaded into a hibernate application when working with hibernate. Hibernate uses this file to establish a connection to the database server. It is an XML file that is used to define the below information. The standard name for this file is hibernate.cfg.xml.
43) What is JPQL?
JPQL stands for Java Persistence Query Language. It is a platform-independent object-oriented query language that is used to perform database operations on persistent entities. It is used to make queries against entities stored in a relational database.
44) What is session.flush() in hibernate?
session.flush() in Hibernate Forces the session to flush. It is used to synchronize session data with the database. When you call session.flush(), the statements are executed in the database but it will not be committed. session.flush() just executes the statements in the database but not commits and statements are NOT IN MEMORY anymore. It just forces the session to flush.
45) For what saveOrUpdate() method is used in hibernate?
Hibernate saveOrUpdate results into insert or update queries based on the provided data. If the data is present in the database, 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 the session is not flushed.
Hibernate saveOrUpdate adds the entity object to persistent context and track any further changes. Any further changes are saved at the time of committing the transaction, like persist.
46) What is hibernate sequence?
SEQUENCE is the generation type recommended by the Hibernate documentation. The generated values are unique per sequence. If you don't specify a sequence name, Hibernate will re-use the same hibernate_sequence for different types.
47) How can we invoke stored procedures in hibernate?
You can use getNamedQuery() or createSQLQuery() to call or invoke stored procedures in Hibernate.
48) What is open session in hibernate?
Open session in hibernate is a method of SessionFactory class that opens a new session. This method always opens a new session and close it once you have completed your operation.
49) What is n+1 select problem in hibernate?
N+1 problem is a performance issue in Object Relational Mapping that fires multiple select queries (N+1 to be exact, where N= number of records in a table) in the database for a single select query at the application layer. Hibernate provides multiple ways to catch and prevent this problem.