Hibernate Interview Questions & Answers

Hibernate is a popular framework of Java which allows an efficient Object Relational mapping using configuration files in XML format. After java objects mapping to database tables, database is used and handled using Java objects without writing complex database queries.

ORM (Object Relational Mapping) is the fundamental concept of Hibernate framework which maps database tables with Java Objects and then provides various API’s to perform different types of operations on the data tables.

Mappings between class properties and table columns are specified in XML file as in the below example:

Configuration interface of hibernate framework is used to configure hibernate. It’s also used to bootstrap hibernate. Mapping documents of hibernate are located using this interface.

We can use extension interfaces in order to add any required functionality which isn’t supported by built-in interfaces.

No, having .hbm.xml extension is a convention and not a requirement for hibernate mapping file names. We can have any extension for these mapping files.

To create a session factory in hibernate, an object of configuration is created first which refers to the path of configuration file and then for that configuration, session factory is created as given in the example below:

POJOs( Plain Old Java Objects) are java beans with proper getter and setter methods for each and every properties.
Use of POJOs instead of simple java classes results in an efficient and well constructed code.

HQL is the query language used in Hibernate which is an extension of SQL. HQL is very efficient, simple and flexible query language to do various type of operations on relational database without writing complex database queries.

In hibernate we can execute stored procedures using code as below:

Criteria is a simple yet powerful API of hibernate which is used to retrieve entities through criteria object composition.

Following are some key benefits of using Hibernate template:
a. Session closing is automated.
b. Interaction with hibernate session is simplified.
c. Exception handling is automated.

We need to add following in hibernate configuration file to enable viewing SQL on the console for debugging purposes:

Following are the two types of collections in hibernate:
a. Sorted Collection
b. Order Collection

Sessionsave() method saves a record only if it’s unique with respect to its primary key and will fail to insert if primary key already exists in the table.
saveOrUpdate() method inserts a new record if primary key is unique and will update an existing record if primary key exists in the table already.

a. Hibernate can be used seamlessly with any type of database as its database independent while in case of JDBC, developer has to write database specific queries.
b. Using hibernate, developer doesn’t need to be an expert of writing complex queries as HQL simplifies query writing process while in case of JDBC, its job of developer to write and tune queries.
c. In case of hibernate, there is no need to create connection pools as hibernate does all connection handling automatically while in case of JDBC, connection pools need to be created.

We can get hibernate statistics using getStatistics() method of SessionFactory class as shown below:
SessionFactory.getStatistics()

If an instance is not associated with any persistent context and also, it has never been associated with any persistent context, then it’s said to be in transient state.

Hibernate provides dirty checking feature which can be used to reduce database write times. Dirty checking feature of hibernate updates only those fields which require a change while keeps others unchanged.

Callback interfaces of hibernate are useful in receiving event notifications from objects. For example, when an object is loaded or deleted, an event is generated and notification is sent using callback interfaces.

When an instance was earlier associated with some persistent context (e.g. a table) and is no longer associated, it’s called to be in detached state.

Following are the four ORM levels in hibernate:
a. Pure Relational
b. Light Object Mapping
c. Medium Object Mapping
d. Full Object Mapping

Transaction management is the process of managing a set of statements or commands. In hibernate; transaction management is done by transaction interface as shown in below code:

We can use any of the following two methods of hibernate configuration:
a. XML based configuration ( using hibernate.cfg.xml file)
b. Programmatic configuration ( Using code logic)

Hibernate supports multiple cache services like EHCache, OSCache, SWARMCache and TreeCache and default cache service of hibernate is EHCache.

In hibernate; we have following two types of mapping associations between entities:
a. One-to-One Association
b. Many-to-Many Association

Hibernate Query By Criteria (QBC) API is used to create queries by manipulation of criteria objects at runtime.

Hibernate provides following four ways to fetch objects from database:
a. Using HQL
b. Using identifier
c. Using Criteria API
d. Using Standard SQL

Database primary key is specified in the configuration file hbm.xml. Generator can also be used to specify how primary key is being created in the database.
In the below example, deptId acts as primary key:

Objects which have been detached and are no longer associated with any persistent entities can be reattached by calling session.merge() method of session class.

Hibernate second level cache can be disabled using any of the following ways:
a. By setting use_second_level_cache as false.
b. By using CACHEMODE.IGNORE
c. Using cache provider as org.hibernate.cache.NoCacheProvider

All the mapping between classes and tables, properties and columns, Java types and SQL types etc is defined in ORM metadata.

With hibernate 3.2, default transaction factory is JDBCTransactionFactory.

Java Applications and components are managed in hibernate by a standard API called JMX API. JMX provides tools for development of efficient and robust distributed, web based solutions.

Hibernate session factory can be bound to JNDI by making configuration changes in hibernate.cfg file.

Object identification can be done in hibernate in following three ways:
a. Using Object Identity: Using == operator.
b. Using Object Equality: Using equals() method.
c. Using database identity: Relational database objects can be identified if they represent same row.

Following fetching strategies are available in hibernate:
1. Join Fetching
2. Batch Fetching
3. Select Fetching
4. Sub-select Fetching

To map java objects with database tables, we need to have Java beans properties names same as column names of a database table. Then mapping is provided in hbm.xml file as given below:

Derived properties are those properties which are not mapped to any columns of a database table. Such properties are calculated at runtime by evaluation of any expressions.

Named SQL queries are those queries which are defined in mapping file and are called as required anywhere.
For example, we can write a SQL query in our XML mapping file as follows:

Then this query can be called as follows:

Load() methods results in an exception if the required records isn’t found in the database while get() method returns null when records against the id isn’t found in the database.
So, ideally we should use Load() method only when we are sure about existence of records against an id.

Version property is used in hibernate to know whether an object is in transient state or in detached state.

In Attribute oriented programming, a developer can add Meta data (attributes) in the java source code to add more significance in the code. For Java (hibernate), attribute oriented programming is enabled by an engine called XDoclet.

session.lock() method of session class is used to reattach an object which has been detached earlier. This method of reattaching doesn’t check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.

Yes, hibernate fully supports polymorphism. Polymorphism queries and polymorphism associations are supported in all mapping strategies of hibernate.

Hibernate has following three inheritance models:
a. Tables Per Concrete Class
b. Table per class hierarchy
c. Table per sub-class

If we don’t want an application to update or delete objects of a class in hibernate, we can make the class as immutable by setting mutable=false

General hibernate flow involving RDBMS is as follows:
a. Load configuration file and create object of configuration class.
b. Using configuration object, create sessionFactory object.
c. From sessionFactory, get one session.
d. Create HQL query.
e. Execute HQL query and get the results. Results will be in the form of a list.

Light Object Mapping is one of the levels of ORM quality in which all entities are represented as classes and they are mapped manually.

Managed associations relate to container management persistence and are bi-directional while hibernate associations are unidirectional.