Hibernate interview questions and answers 👇

  1. Hibernate General Interview Questions
  2. Hibernate Advanced Interview Questions
  3. Advanced


Hibernate General Interview Questions

What are the advantages of Hibernate over JDBC?

View answer

The advantages of Hibernate over JDBC are listed below:

  • Clean Readable Code: Using hibernate, helps in eliminating a lot of JDBC API-based boiler-plate codes, thereby making the code look cleaner and readable.
  • HQL (Hibernate Query Language): Hibernate provides HQL which is closer to Java and is object-oriented in nature. This helps in reducing the burden on developers for writing database independent queries. In JDBC, this is not the case. A developer has to know the database-specific codes.
  • Transaction Management: JDBC doesn't support implicit transaction management. It is upon the developer to write transaction management code using commit and rollback methods. Whereas, Hibernate implicity provides this feature.
  • Exception Handling: Hibernate wraps the JDBC exceptions and throws unchecked exceptions like JDBCException or HibernateException. This along with the built-in transaction management system helps developers to avoid writing multiple try-catch blocks to handle exceptions. In the case of JDBC, it throws a checked exception called SQLException thereby mandating the developer to write try-catch blocks to handle this exception at compile time.
  • Special Features: Hibernate supports OOPs features like inheritance, associations and also supports collections. These are not available in JDBC.

What are some of the important interfaces of Hibernate framework?

View answer

Hibernate core interfaces are:

  • Configuration
  • SessionFactory
  • Session
  • Criteria
  • Query
  • Transaction

What is a Session in Hibernate?

View answer

A session is an object that maintains the connection between Java object application and database. Session also has methods for storing, retrieving, modifying or deleting data from database using methods like persist(), load(), get(), update(), delete(), etc. Additionally, It has factory methods to return Query, Criteria, and Transaction objects.

What is a SessionFactory?

View answer

SessionFactory provides an instance of Session. It is a factory class that gives the Session objects based on the configuration parameters in order to establish the connection to the database. As a good practice, the application generally has a single instance of SessionFactory. The internal state of a SessionFactory which includes metadata about ORM is immutable, i.e once the instance is created, it cannot be changed.

This also provides the facility to get information like statistics and metadata related to a class, query executions, etc. It also holds second-level cache data if enabled.

What do you think about the statement - “session being a thread-safe object”?

View answer

No, Session is not a thread-safe object which means that any number of threads can access data from it simultaneously.

Can you explain what is lazy loading in hibernate?

View answer

Lazy loading is mainly used for improving the application performance by helping to load the child objects on demand.

It is to be noted that, since Hibernate 3 version, this feature has been enabled by default. This signifies that child objects are not loaded until the parent gets loaded.

What can you tell about Hibernate Configuration File?

View answer

Hibernate Configuration File or hibernate.cfg.xml is one of the most required configuration files in Hibernate. By default, this file is placed under the src/main/resource folder. The file contains database related configurations and session-related configurations. Hibernate facilitates providing the configuration either in an XML file (like hibernate.cfg.xml) or a properties file (like hibernate.properties).

This file is used to define the below information:

  • Database connection details: Driver class, URL, username, and password.
  • There must be one configuration file for each database used in the application, suppose if we want to connect with 2 databases, then we must create 2 configuration files with different names.
  • Hibernate properties: Dialect, show_sql, second_level_cache, and mapping file names.

How do you create an immutable class in hibernate?

View answer

Immutable class in hibernate creation could be in the following way. If we are using the XML form of configuration, then a class can be made immutable by markingmutable=false. The default value is true there which indicating that the class was not created by default.

In the case of using annotations, immutable classes in hibernate can also be created by using @Immutable annotation.

Can you explain the concept behind Hibernate Inheritance Mapping?

View answer

Java is an Object-Oriented Programming Language and Inheritance is one of the most important pillars of object-oriented principles. To represent any models in Java, inheritance is most commonly used to simplify and simplify the relationship. But, there is a catch. Relational databases do not support inheritance. They have a flat structure.

Hibernate’s Inheritance Mapping strategies deal with solving how to hibernate being an ORM tries to map this problem between the inheritance of Java and flat structure of Databases.

Consider the example where we have to divide InterviewBitEmployee into Contract and Permanent Employees represented by IBContractEmployee and IBPermanentEmployee classes respectively. Now the task of hibernate is to represent these 2 employee types by considering the below restrictions:

The general employee details are defined in the parent InterviewBitEmployee class.

Contract and Permanent employee-specific details are stored in IBContractEmployee and IBPermanentEmployee classes respectively.

There are different inheritance mapping strategies available:

  • Single Table Strategy
  • Table Per Class Strategy
  • Mapped Super Class Strategy
  • Joined Table Strategy

Is hibernate prone to SQL injection attack?

View answer

SQL injection attack is a serious vulnerability in terms of web security wherein an attacker can interfere with the queries made by an application/website to its database thereby allowing the attacker to view sensitive data which are generally irretrievable. It can also give the attacker to modify/ remove the data resulting in damages to the application behavior.

Hibernate does not provide immunity to SQL Injection. However, following good practices avoids SQL injection attacks. It is always advisable to follow any of the below options:

Incorporate Prepared Statements that use Parameterized Queries. Use Stored Procedures. Ensure data sanity by doing input validation.

Explain hibernate mapping file

View answer

Hibernate mapping file is an XML file that is used for defining the entity bean fields and corresponding database column mappings. These files are useful when the project uses third-party classes where JPA annotations provided by hibernating cannot be used.

In the previous example, we have defined the mapping resource as “InterviewBitEmployee.hbm.xml” in the config file. Let us see what that sample hbm.xml file looks like:

<!DOCTYPE hibernate-mapping PUBLIC 
                                        "-//Hibernate/Hibernate Mapping DTD//EN"
                                        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
                                        
                                        <hibernate-mapping>
                                           <!-- What class is mapped to what database table-->
                                          <class name = "InterviewBitEmployee" table = "InterviewBitEmployee">
                                        
                                             <meta attribute = "class-description">
                                                This class contains the details of employees of InterviewBit. 
                                             </meta>
                                        
                                             <id name = "id" type = "int" column = "employee_id">
                                                <generator class="native"/>
                                             </id>
                                        
                                             <property name = "fullName" column = "full_name" type = "string"/>
                                             <property name = "email" column = "email" type = "string"/>
                                        
                                          </class>
                                        </hibernate-mapping>
                                        

What are the most commonly used annotations available to support hibernate mapping?

View answer

Hibernate framework provides support to JPA annotations and other useful annotations in the org.hibernate.annotations package. Some of them are as follows:

javax.persistence.Entity: This annotation is used on the model classes by using “@Entity” and tells that the classes are entity beans. javax.persistence.Table: This annotation is used on the model classes by using “@Table” and tells that the class maps to the table name in the database. javax.persistence.Access: This is used as “@Access” and is used for defining the access type of either field or property. When nothing is specified, the default value taken is “field”. javax.persistence.Id: This is used as “@Id” and is used on the attribute in a class to indicate that attribute is the primary key in the bean entity. javax.persistence.EmbeddedId: Used as “@EmbeddedId” upon the attribute and indicates it is a composite primary key of the bean entity. javax.persistence.Column: “@Column” is used for defining the column name in the database table. javax.persistence.GeneratedValue: “@GeneratedValue” is used for defining the strategy used for primary key generation. This annotation is used along with javax.persistence.GenerationType enum. javax.persistence.OneToOne: “@OneToOne” is used for defining the one-to-one mapping between two bean entities. Similarly, hibernate provides OneToMany, ManyToOne and ManyToMany annotations for defining different mapping types. org.hibernate.annotations.Cascade: “@Cascade” annotation is used for defining the cascading action between two bean entities. It is used with org.hibernate.annotations.CascadeType enum to define the type of cascading. Following is a sample class where we have used the above listed annotations: package com.dev.interviewbit.model; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table;

import org.hibernate.annotations.Cascade;

@Entity @Table(name = "InterviewBitEmployee") @Access(value=AccessType.FIELD) public class InterviewBitEmployee {

@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "employee_id") private long id;

@Column(name = "full_name") private String fullName;

@Column(name = "email") private String email;

@OneToOne(mappedBy = "employee") @Cascade(value = org.hibernate.annotations.CascadeType.ALL) private Address address;

//getters and setters methods }

Explain Hibernate architecture

View answer

The Hibernate architecture consists of many objects such as a persistent object, session factory, session, query, transaction, etc. Applications developed using Hibernate is mainly categorized into 4 parts:

  • Java Application
  • Hibernate framework - Configuration and Mapping Files
  • Internal API -
  1. JDBC (Java Database Connectivity)
  2. JTA (Java Transaction API)
  3. JNDI (Java Naming Directory Interface).
  • Database - MySQL, PostGreSQL, Oracle, etc

The main elements of Hibernate framework are:

  • SessionFactory: This provides a factory method to get session objects and clients of ConnectionProvider. It holds a second-level cache (optional) of data.
  • Session: This is a short-lived object that acts as an interface between the java application objects and database data.
  1. The session can be used to generate transaction, query, and criteria objects.
  2. It also has a mandatory first-level cache of data.
  • Transaction: This object specifies the atomic unit of work and has methods useful for transaction management. This is optional.
  • ConnectionProvider: This is a factory of JDBC connection objects and it provides an abstraction to the application from the DriverManager. This is optional.
  • TransactionFactory: This is a factory of Transaction objects. It is optional.

What is criteria API in hibernate?

View answer

Criteria API in Hibernate helps developers to build dynamic criteria queries on the persistence database. Criteria API is a more powerful and flexible alternative to HQL (Hibernate Query Language) queries for creating dynamic queries.

This API allows to programmatically development criteria query objects. The org.hibernate.Criteria interface is used for these purposes. The Session interface of hibernate framework has createCriteria() method that takes the persistent object’s class or its entity name as the parameters and returns persistence object instance the criteria query is executed.

It also makes it very easy to incorporate restrictions to selectively retrieve data from the database. It can be achieved by using the add() method which accepts the org.hibernate.criterion.Criterion object representing individual restriction.

Usage examples:

To return all the data of InterviewBitEmployee entity class.

Criteria criteria = session.createCriteria(InterviewBitEmployee.class); Listresults = criteria.list(); To retrive objects whose property has value equal to the restriction, we use Restrictions.eq() method. For example, to fetch all records with name ‘Hibernate’:

Criteria criteria= session.createCriteria(InterviewBitEmployee.class); criteria.add(Restrictions.eq("fullName","Hibernate")); Listresults = criteria.list(); To get objects whose property has the value “not equal to” the restriction, we use Restrictions.ne() method. For example, to fetch all the records whose employee’s name is not Hibernate:

Criteria criteria= session.createCriteria(InterviewBitEmployee.class); criteria.add(Restrictions.ne("fullName","Hibernate")); Listresults = criteria.list() To retrieve all objects whose property matches a given pattern, we use Restrictions.like() (for case sensitivenes) and Restrictions.ilike()(for case insensitiveness)

Criteria criteria= session.createCriteria(InterviewBitEmployee.class); criteria.add(Restrictions.like("fullName","Hib%",MatchMode.ANYWHERE)); Listresults = criteria.list(); Similarly, it also has other methods like isNull(), isNotNull(), gt(), ge(), lt(), le() etc for adding more varieties of restrictions. It has to be noted that for Hibernate 5 onwards, the functions returning an object of typeCriteria are deprecated. Hibernate 5 version has provided interfaces like CriteriaBuilder and CriteriaQuery to serve the purpose:

javax.persistence.criteria.CriteriaBuilder javax.persistence.criteria.CriteriaQuery

// Create CriteriaBuilder CriteriaBuilder builder = session.getCriteriaBuilder();

// Create CriteriaQuery CriteriaQuerycriteria = builder.createQuery(YourClass.class); For introducing restrictions in CriteriaQuery, we can use the CriteriaQuery.where method which is analogous to using the WHERE clause in a JPQL query.

What is HQL?

View answer

Hibernate Query Language (HQL) is used as an extension of SQL. It is very simple, efficient, and very flexible for performing complex operations on relational databases without writing complicated queries. HQL is the object-oriented representation of query language, i.e instead of using table name, we make use of the class name which makes this language independent of any database.

This makes use of the Query interface provided by Hibernate. The Query object is obtained by calling the createQuery() method of the hibernate Session interface.

Following are the most commonly used methods of query interface:

public int executeUpdate() : This method is used to run the update/delete query. public List list(): This method returns the result as a list. public Query setFirstResult(int rowNumber): This method accepts the row number as the parameter using which the record of that row number would be retrieved. public Query setMaxResult(int rowsCount): This method returns a maximum up to the specified rowCount while retrieving from the database. public Query setParameter(int position, Object value): This method sets the value to the attribute/column at a particular position. This method follows the JDBC style of the query parameter. public Query setParameter(String name, Object value): This method sets the value to a named query parameter. Example: To get a list of all records from InterviewBitEmployee Table:

Query query=session.createQuery("from InterviewBitEmployee");
Listlist=query.list();
System.out.println(list.get(0));

What does session.lock() method in hibernate do?

View answer

session.lock() method is used to reattach a detached object to the session. session.lock() method does not check for any data synchronization between the database and the object in the persistence context and hence this reattachment might lead to loss of data synchronization.

When is merge() method of the hibernate session useful?

View answer

Merge() method can be used for updating existing values. The specialty of this method is, once the existing values are updated, the method creates a copy from the entity object and returns it. This result object goes into the persistent context and is then tracked for any changes. The object that was initially used is not tracked.

Collection mapping can be done using One-to-One and Many-to-One Associations. What do you think?

View answer

False, collection mapping is possible only with One-to-Many and Many-to-Many associations.

Can you tell the difference between setMaxResults() and setFetchSize() of Query?

View answer

setMaxResults() the function works similar to LIMIT in SQL. Here, we set the maximum number of rows that we want to be returned. This method is implemented by all database drivers.

setFetchSize() works for optimizing how Hibernate sends the result to the caller for example: are the results buffered, are they sent in different size chunks, etc. This method is not implemented by all the database drivers.

Does Hibernate support Native SQL Queries?

View answer

Yes, it does. Hibernate provides the createSQLQuery() method to let a developer call the native SQL statement directly and returns a Query object.

Consider the example where you want to get employee data with the full name “Hibernate”. We don’t want to use HQL-based features, instead, we want to write our own SQL queries. In this case, the code would be:

Query query = session.createSQLQuery( "select * from interviewbit_employee ibe where ibe.fullName = :fullName") .addEntity(InterviewBitEmployee.class) .setParameter("fullName", "Hibernate"); //named parameters List result = query.list(); Alternatively, native queries can also be supported when using NamedQueries.

What is the difference between first level cache and second level cache?

View answer

Hibernate has 2 cache types. First level and second level cache for which the difference is given below:

First Level Cache:

  • This is local to the Session object and cannot be shared between multiple sessions.
  • This cache is enabled by default and there is no way to disable it.
  • The first level cache is available only until the session is open, once the session is closed, the first level cache is destroyed.

Second Level Cache:

  • This cache is maintained at the SessionFactory level and shared among all sessions in Hibernate.
  • This is disabled by default, but we can enable it through configuration.
  • The second-level cache is available through the application’s life cycle, it is only destroyed and recreated when an application is restarted.

If an entity or object is loaded by calling the get() method then Hibernate first checked the first level cache, if it doesn’t find the object then it goes to the second level cache if configured. If the object is not found then it finally goes to the database and returns the object, if there is no corresponding row in the table then it returns null.

Can you tell the difference between getCurrentSession and openSession methods?

View answer

Both the methods are provided by the Session Factory. The main differences are given below:

getCurrentSession()

  • This method returns the session bound to the context.
  • This session object scope belongs to the hibernate context and to make this work hibernate configuration file has to be modified by addingthread. If not added, then using the method would throw an HibernateException.
  • This session object gets closed once the session factory is closed.
  • In a single-threaded environment, this method is faster than openSession().

openSession()

  • This method always opens a new session.
  • A new session object has to be created for each request in a multi-threaded environment. Hence, you need not configure any property to call this method.
  • It's the developer’s responsibility to close this object once all the database operations are done.
  • In single threaded environment, it is slower than getCurrentSession()single-threadeda

Apart from these two methods, there is another method openStatelessSession() and this method returns a stateless session object.

Differentiate between save() and saveOrUpdate() methods in hibernate session.

View answer

Both the methods save records to the table in the database in case there are no records with the primary key in the table. However, the main differences between these two are listed below:

save()

  • save() generates a new identifier and INSERT record into a database.
  • The insertion fails if the primary key already exists in the table.
  • The return type is Serializable which is the newly generated identifier id value as a Serializable object.
  • This method is used to bring only a transient object to a persistent state.

saveOrUpdate()

  • Session.saveOrUpdate() can either INSERT or UPDATE based upon existence of a record.
  • In case the primary key already exists, then the record is updated.
  • The return type of the saveOrUpdate() method is void.
  • This method can bring both transient (new) and detached (existing) objects into a persistent state. It is often used to re-attach a detached object into a Session.

Clearly, saveOrUpdate() is more flexible in terms of use but it involves extra processing to find out whether a record already exists in the table or not.

Differentiate between get() and load() in Hibernate session

View answer

These are the methods to get data from the database. The primary differences between get and load in Hibernate are given below:

get()

  • This method gets the data from the database as soon as it is called.
  • The database is hit every time the method is called.
  • The method returns null if the object is not found.
  • This method should be used if we are unsure about the existence of data in the database.

load()

  • This method returns a proxy object and loads the data only when it is required.
  • The database is hit only when it is really needed and this is called Lazy Loading which makes the method better.
  • The method throws ObjectNotFoundException if the object is not found.
  • This method is to be used when we know for sure that the data is present in the database.

List some of the databases supported by Hibernate.

View answer

Some of the databases supported by Hibernate are:

  • DB2
  • MySQL
  • Oracle
  • Sybase SQL Server
  • Informix Dynamic Server
  • HSQL
  • PostgreSQL
  • FrontBase

Hibernate Advanced Interview Questions

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

View answer

Hibernate framework internally uses Reflection API for creating entity bean instances when get() or load() methods are called. The method Class.newInstance() is used which requires a no-args constructor to be present. When we don't have this constructor in the entity beans, then hibernate fails to instantiate the bean and hence it throws HibernateException.

Can we declare the Entity class final?

View answer

No, we should not define the entity class final because hibernate uses proxy classes and objects for lazy loading of data and hits the database only when it is absolutely needed. This is achieved by extending the entity bean. If the entity class (or bean) is made final, then it cant be extended and hence lazy loading can not be supported.

What are the states of a persistent entity?

View answer

A persistent entity can exist in any of the following states:

Transient:

This state is the initial state of any entity object. Once the instance of the entity class is created, then the object is said to have entered a transient state. These objects exist in heap memory. In this state, the object is not linked to any session. Hence, it is not related to any database due to which any changes in the data object don't affect the data in the database. InterviewBitEmployee employee=new InterviewBitEmployee(); //The object is in the transient state.
employee.setId(101);
employee.setFullName("Hibernate"); employee.setEmail("hibernate@interviewbit.com"); Persistent:

This state is entered whenever the object is linked or associated with the session. An object is said to be in a persistence state whenever we save or persist an object in the database. Each object corresponds to the row in the database table. Any modifications to the data in this state cause changes in the record in the database. Following methods can be used upon the persistence object:

session.save(record);
session.persist(record);
session.update(record);
session.saveOrUpdate(record);
session.lock(record);
session.merge(record); Detached:

The object enters this state whenever the session is closed or the cache is cleared. Due to the object being no longer part of the session, any changes in the object will not reflect in the corresponding row of the database. However, it would still have its representation in the database. In case the developer wants to persist changes of this object, it has to be reattached to the hibernate session. In order to achieve the reattachment, we can use the methods load(), merge(), refresh(), update(), or save() methods on a new session by using the reference of the detached object. The object enters this state whenever any of the following methods are called:

session.close(); session.clear(); session.detach(record); session.evict(record);

Explain Query Cache

View answer

Hibernate framework provides an optional feature called cache region for the queries’ resultset. Additional configurations have to be done in code in order to enable this. The query cache is useful for those queries which are most frequently called with the same parameters. This increases the speed of the data retrieval and greatly improves performance for commonly repetitive queries.

This does not cache the state of actual entities in the result set but it only stores the identifier values and results of the value type. Hence, query cache should be always used in association with second-level cache.

Configuration:

In the hibernate configuration XML file, set the use_query_cache property to true as shown below:

true

In the code, we need to do the below changes for the query object: Query query = session.createQuery("from InterviewBitEmployee"); query.setCacheable(true); query.setCacheRegion("IB_EMP");

Can you tell something about the N+1 SELECT problem in Hibernate?

View answer

N+1 SELECT problem is due to the result of using lazy loading and on-demand fetching strategy. Let's take an example. If you have an N items list and each item from the list has a dependency on a collection of another object, say bid. In order to find the highest bid for each item while using the lazy loading strategy, hibernate has to first fire 1 query to load all items and then subsequently fire N queries to load big of each item. Hence, hibernate actually ends up executing N+1 queries.

How to solve N+1 SELECT problem in Hibernate?

View answer

Some of the strategies followed for solving the N+1 SELECT problem are:

  • Pre-fetch the records in batches which helps us to reduce the problem of N+1 to (N/K) + 1 where K refers to the size of the batch.
  • Subselect the fetching strategy
  • As last resort, try to avoid or disable lazy loading altogether.

What are the concurrency strategies available in hibernate?

View answer

Concurrency strategies are the mediators responsible for storing and retrieving items from the cache. While enabling second-level cache, it is the responsibility of the developer to provide what strategy is to be implemented to decide for each persistent class and collection.

Following are the concurrency strategies that are used:

  • Transactional: This is used in cases of updating data that most likely causes stale data and this prevention is most critical to the application.
  • Read-Only: This is used when we don't want the data to be modified and can be used for reference data only.
  • Read-Write: Here, data is mostly read and is used when the prevention of stale data is of critical importance.
  • Non-strict-Read-Write: Using this strategy will ensure that there wouldn't be any consistency between the database and cache. This strategy can be used when the data can be modified and stale data is not of critical concern

What is Single Table Strategy?

View answer

Single Table Strategy is a hibernate’s strategy for performing inheritance mapping. This strategy is considered to be the best among all the other existing ones. Here, the inheritance data hierarchy is stored in the single table by making use of a discriminator column which determines to what class the record belongs.

For the example defined in the Hibernate Inheritance Mapping question above, if we follow this single table strategy, then all the permanent and contract employees’ details are stored in only one table called InterviewBitEmployee in the database and the employees would be differentiated by making use of discriminator column named employee_type.

Hibernate provides @Inheritance annotation which takes strategy as the parameter. This is used for defining what strategy we would be using. By giving them value, InheritanceType.SINGLE_TABLE signifies that we are using a single table strategy for mapping.

  • @DiscriminatorColumn is used for specifying what is the discriminator column of the table in the database corresponding to the entity.
  • @DiscriminatorValue is used for specifying what value differentiates the records of two types. The code snippet would be like this:

InterviewBitEmployee class:

@Entity @Table(name = "InterviewBitEmployee") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "employee_type") @NoArgsConstructor @AllArgsConstructor public class InterviewBitEmployee { @Id @Column(name = "employee_id") private String employeeId; private String fullName; private String email; } InterviewBitContractEmployee class:

@Entity @DiscriminatorValue("contract") @NoArgsConstructor @AllArgsConstructor public class InterviewBitContractEmployee extends InterviewBitEmployee { private LocalDate contractStartDate; private LocalDate contractEndDate; private String agencyName; } InterviewBitPermanentEmployee class:

@Entity @DiscriminatorValue("permanent") @NoArgsConstructor @AllArgsConstructor public class InterviewBitPermanentEmployee extends InterviewBitEmployee { private LocalDate workStartDate; private int numberOfLeaves; }

Can you tell something about Named SQL Query

View answer

A named SQL query is an expression represented in the form of a table. Here, SQL expressions to select/retrieve rows and columns from one or more tables in one or more databases can be specified. This is like using aliases to the queries.

In hibernate, we can make use of @NameQueries and @NameQuery annotations.

@NameQueries annotation is used for defining multiple named queries. @NameQuery annotation is used for defining a single named query. Code Snippet: We can define Named Query as shown below

@NamedQueries(
{
@NamedQuery(
name = "findIBEmployeeByFullName",
query = "from InterviewBitEmployee e where e.fullName = :fullName"
)
}
)
:fullName refers to the parameter that is programmer defined and can be set using the query.setParameter method while using the named query.

Usage:

TypedQuery query = session.getNamedQuery("findIBEmployeeByFullName");
query.setParameter("fullName","Hibernate");
ListibEmployees = query.getResultList(); The getNamedQuery method takes the name of the named query and returns the query instance.

What are the benefits of NamedQuery?

View answer

In order to understand the benefits of NamedQuery, let's first understand the disadvantage of HQL and SQL. The main disadvantage of having HQL and SQL scattered across data access objects is that it makes the code unreadable. Hence, as good practice, it is recommended to group all HQL and SQL codes in one place and use only their reference in the actual data access code. In order to achieve this, Hibernate gives us named queries.

A named query is a statically defined query with a predefined unchangeable query string. They are validated when the session factory is created, thus making the application fail fast in case of an error.

How to complete a transaction in Hibernate?

View answer

There are two distinct actions if you’re looking to complete a transaction in hibernate: • Commit • Rollback

Once a transaction is committed, the transaction data is written to the database. In case there is a rollback, the data exchange is flushed and never written or updated to the database.

Can you touch upon the different types of relationships available in Hibernate mapping?

View answer

Hibernate consists of three different types of relationships: • One-to-One mapping • One-to-Many mapping • Many-to-Many mapping

What is the purpose of Session.beginTransaction()?

View answer

Hibernate keeps a log of every data exchange with the help of a transaction. Thereon, in case a new exchange of date is about to get initiated, the function Session.beginTransaction is executed in order to begin the transaction.

Where is object/relational mappings defined in Hibernate?

View answer

An XML document is where object/relational mappings are usually defined in. This mapping file gives instructions to Hibernate on how to accurately map the defined class/classes to the database tables. In addition, the format .hbm.xml. should be used to save the file with the mapping document.

What is lazy loading?

View answer

Lazy loading is defined as a technique in which objects are loaded on an on-demand basis. It has been enabled by default since the advent of Hibernate 3 to ensure that child objects are not loaded when the parent is.

What are the ways to express joins in HQL?

View answer

HQL allows you to express joins in four ways: • An implicit association join • A fetch join in the FROM clause • A theta-style join in the WHERE clause • An ordinary join in the FROM clause

How would you define automatic dirty checking?

View answer

Automatic dirty checking can be defined as a feature that helps us in saving the effort of explicitly asking Hibernate to update the database every time we modify or make changes to the state of an object inside a transaction.

Explain the different ways Hibernate manages concurrency?

View answer

Hibernate has numerous ways of managing concurrency. They are as listed below: • Automatic versioning • Detached object • Extended user sessions

Can you detail out the various collection types in Hibernate?

View answer

There are five distinct collection types that are used in hibernate for one-to-many relationship mappings. • Bag • Set • List • Array • Map

Explain the difference between hibernate and Spring?

View answer

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

In addition to the above-mentioned list of questions, here are a few more Frequently Asked Questions which we have put together to help you crack your all-important Hibernate interviews.

• How many concurrent Hibernate sessions can exist at any point in time in an application? • Is SessionFactory a thread-safe object? • Can you explain the role Session interface plays in Hibernate? • Describe the process of switching between relational databases without code changes. • Explain the difference between the session.get() method and the session.load() method. • Is it possible to use Hibernate to map persistent entity POJO to XML files? • List out all the different states of an instance in Hibernate. • Can you describe the different contextual sessions in Hibernate? • Touch upon the pros of Hibernate Criteria API. • Explain the benefit of Hibernate Tools Eclipse plugin. • Describe component mapping in Hibernate.

What is meant by Hibernate tuning?

View answer

Optimizing the performance of Hibernate applications is known as Hibernate tuning.

The performance tuning strategies for Hibernate are:

  • SQL Optimization
  • Session Management
  • Data Caching

What is Transaction Management in Hibernate? How does it work?

View answer

Transaction Management is a property which is present in the Spring framework. Now, what role does it play in Hibernate?

Transaction Management is a process of managing a set of commands or statements. In hibernate, Transaction Management is done by transaction interface. It maintains abstraction from the transaction implementation (JTA, JDBC). A transaction is associated with Session and is instantiated by calling session.beginTransaction().

How do you integrate Hibernate with Struts2 or Servlet web applications?

View answer

You can integrate any Struts application with Hibernate. There are no extra efforts required.

  1. Register a custom ServletContextListener.
  2. In the ServletContextListener class, first, initialize the Hibernate Session, store it in the servlet context.
  3. Action class helps in getting the Hibernate Session from the servlet context, and perform other Hibernate task as normal.

What are the different states of a persistent entity?

View answer

It may exist in one of the following 3 states:

  • Transient: This is not associated with the Session and has no representation in the database.
  • Persistent: You can make a transient instance persistent by associating it with a Session.
  • Detached: If you close the Hibernate Session, the persistent instance will become a detached instance.

How can the primary key be created by using Hibernate?

View answer

A Primary key is a special relational database table column designated to uniquely identify all table records. It is specified in the configuration file hbm.xml. The generator can also be used to specify how a Primary key can be created in the database.

<id name="ClassID" type="string" >
                                        <column name= "columnID" length="10" >
                                        <generator/>
                                        </id>
                                        

Explain about Hibernate Proxy and how it helps in Lazy loading?

View answer

  • Hibernate uses a proxy object in order to support Lazy loading.
  • When you try loading data from tables, Hibernate doesn’t load all the mapped objects.
  • After you reference a child object through getter methods, if the linked entity is not present in the session cache, then the proxy code will be entered to the database and load the linked object.
  • It uses Java assist to effectively and dynamically generate sub-classed implementations of your entity objects.

How can we see Hibernate generated SQL on console?

View answer

In order to view the SQL on a console, you need to add following in Hibernate configuration file to enable viewing SQL on the console for debugging purposes:

<property name="show_sql">true</property>

What is Query Cache in Hibernate?

View answer

Hibernate implements a separate cache region for queries resultset that integrates with the Hibernate second-level cache. This is also an optional feature and requires a few more steps in code.

What is the benefit of Native SQL query support in Hibernate?

View answer

Hibernate provides an option to execute Native SQL queries through the use of the SQLQuery object. For normal scenarios, it is however not the recommended approach because you might lose other benefits like Association and Hibernate first-level caching.

Native SQL Query comes handy when you want to execute database-specific queries that are not supported by Hibernate API such query hints or the Connect keyword in Oracle Database.

What is Named SQL Query?

View answer

Hibernate provides another important feature called Named Query using which you can define at a central location and use them anywhere in the code.

You can create named queries for both HQL as well as for Native SQL. These Named Queries can be defined in Hibernate mapping files with the help of JPA annotations @NamedQuery and @NamedNativeQuery.

When do you use merge() and update() in Hibernate?

View answer

This is one of the tricky Hibernate Interview Questions asked.

  • update(): If you are sure that the Hibernate Session does not contain an already persistent instance with the same id .
  • merge(): Helps in merging your modifications at any time without considering the state of the Session.

Difference between get() vs load() method in Hibernate?

View answer

This is one of the most frequently asked Hibernate Interview Questions. The key difference between the get() and load() method is:

load(): It will throw an exception if an object with an ID passed to them is not found. get(): Will return null.

load(): It can return proxy without hitting the database unless required. get(): It always goes to the database.

So sometimes using load() can be faster than the get() method.

Difference between the first and second level cache in Hibernate?

View answer

The first-level cache is maintained at Session level while the second level cache is maintained at a SessionFactory level and is shared by all sessions.

Difference between Session and SessionFactory in Hibernate?

View answer

This is yet another popular Hibernate Interview Question asked.

  • A Session is a single-threaded, short-lived object. It provides the first-level cache.
  • SessionFactory is immutable and shared by all Session. It also lives until the Hibernate is running. It also provides the second-level cache.

Difference between save() and saveOrUpdate() method of Hibernate?

View answer

Even though save() and saveOrUpdate() method is used to store an object into Database, the key difference between them is that save() can only Insert records but saveOrUpdate() can either Insert or Update records.

Difference between sorted and ordered collection in Hibernate?

View answer

Sorted collection sort the data in JVM’s heap memory using Java’s collection framework sorting methods. The ordered collection is sorted using order by clause in the database itself.

Note: A sorted collection is more suited for small dataset but for a large dataset, it’s better to use ordered collection to avoid

Difference between the transient, persistent and detached state in Hibernate?

View answer

Transient state: New objects are created in the Java program but are not associated with any Hibernate Session.

Persistent state: 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.

Detached state: You can re-attach a detached object to Hibernate sessions by calling either update() or saveOrUpdate() method.

Difference between managed associations and Hibernate associations?

View answer

Managed associations: Relate to container management persistence and are bi-directional.

Hibernate Associations: These associations are unidirectional.

What are the best practices that Hibernate recommends for persistent classes?

View answer

  • All Java classes that will be persisted need a default constructor.
  • All classes should contain an ID in order to allow easy identification of your objects within Hibernate and the database. This property maps to the primary key column of a database table.
  • All attributes that will be persisted should be declared private and have getXXX and setXXX methods defined in the JavaBean style.
  • A central feature of Hibernate, proxies, depends upon the persistent class being either non-final, or the implementation of an interface that declares all public methods.
  • All classes that do not extend or implement some specialized classes and interfaces required by the EJB framework.

What are the best practices to follow with Hibernate framework?

View answer

  • Always check the primary key field access, if it’s generated at the database layer then you should not have a setter for this.
  • By default hibernate set the field values directly, without using setters. So if you want Hibernate to use setters, then make sure proper access is defined as @Access(value=AccessType.PROPERTY).
  • If access type is property, make sure annotations are used with getter methods and not setter methods. Avoid mixing of using annotations on both filed and getter methods.
  • Use native sql query only when it can’t be done using HQL, such as using the database-specific feature.
  • If you have to sort the collection, use ordered list rather than sorting it using Collection API.
  • Use named queries wisely, keep it at a single place for easy debugging. Use them for commonly used queries only. For entity-specific query, you can keep them in the entity bean itself.
  • For web applications, always try to use JNDI DataSource rather than configuring to create a connection in hibernate.
  • Avoid Many-to-Many relationships, it can be easily implemented using bidirectional One-to-Many and Many-to-One relationships.
  • For collections, try to use Lists, maps and sets. Avoid array because you don’t get benefit of lazy loading.
  • Do not treat exceptions as recoverable, roll back the Transaction and close the Session. If you do not do this, Hibernate cannot guarantee that the in-memory state accurately represents the persistent state.
  • Prefer DAO pattern for exposing the different methods that can be used with entity bean
  • Prefer lazy fetching for associations.

How do we create session factory in hibernate?

View answer

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:

Configuration config = new Configuration();
                                        config.addResource(&amp;quot;myinstance/configuration.hbm.xml&amp;quot;);
                                        config.setProperties( System.getProperties() );
                                        SessionFactory sessions = config.buildSessionFactory();
                                        

What is criteria API?

View answer

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

How can we get hibernate statistics?

View answer

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

SessionFactory.getStatistics()

What are the advantages of Hibernate?

View answer

Here’s a list of Hibernate’s many advantages:

  • It’s fast
  • It’s lightweight and open source
  • It reduces code length, removing boilerplate code, freeing up developers for other tasks
  • It strengthens the object-level relationship
  • It facilitates the generation of independent database queries
  • It provides resources for creating tables automatically
  • It’s easy to integrate with other Java Enterprise Edition (EE) frameworks.

What is “persistence”?

View answer

In the context of Java, persistence describes data and objects that last beyond the process used to create them.

Name some databases that Hibernate supports.

View answer

Hibernate supports databases like:

  • DB2/NT
  • FrontBase
  • HSQL Database Engine
  • Informix Dynamic Server
  • Microsoft SQL Server Database
  • MySQL
  • Oracle
  • PostgreSQL
  • SQL Server
  • Sybase

What design patterns does the Hibernate framework use?

View answer

Some design patterns include:

  • Data Mapper, which moves data between objects and a database, keeping them independent of each other and the mapper
  • Domain Model Pattern, which is a domain object model that incorporates both behavior and data
  • Proxy Pattern, for lazy loading
  • Factory pattern in SessionFactory

Name the states that a persistent entity exists in.

View answer

Persistent entities exist in only three states:

  • Transient
  • Persistent
  • Detached

How many ways can an object be fetched from Hibernate’s database?

View answer

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

  • Criteria API
  • HQL
  • The identifier
  • Standard SQL

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

View answer

There are three ways to disable the cache:

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

How to create database applications in Java with the use of Hibernate?

View answer

Hibernate makes the creation of database applications in Java simple. The steps involved are -

  1. First, we have to write the java object.
  2. A mapping file (XML) needs to be created that shows the relationship between class attributes and the database.
  3. Lastly, Hibernate APIs have to be deployed in order to store the persistent objects.

Can you explain the "version field"?

View answer

In case, offline information, backed by a database, is being changed, then data integrity at the application level is highly important. A versioning protocol, which is an advanced level of locking, is needed to support it. At this point in time, the use of the version field comes in. However, the implementation and design process is up to users, primarily developers.

What are your views on the function addClass?

View answer

The function addClass translates the name, basically from Java class to a file name. Subsequently, the Java ClassLoader loads the translated file as the input stream. The translation between one form to the other, precisely, from Java class to a file name, is called the add class function.

Can you explain the role of addDirectory() and addjar() methods?

View answer

The addDirectory() and addjar() methods in Hibernate allow users to load Hibernate documents. Both addDirectory() and addjar() methods play a significant role in simplifying a range of processes, such as layout, refactoring, configuration, and many more. AddDirectory() and addjar() are greatly useful, especially when adding hibernate mapping with initialization files.

What are your thoughts on file mapping in Hibernate?

View answer

File mapping is the core function of Hibernate. It is a prime tool in database mapping. Typically, the mapping takes place between attributes and classes. Application of tags, after mapping the files in a database, can indicate the primary key.

View answer

Can you share your views on mapping description files?

View answer

Mapping description files are used by Hibernate to configure functions. Mapping description files have the *.hbm extension, which facilitates the mapping between database tables and Java class. Whether to use mapping description files or not, entirely depends on business entities.

What is a polymorphic association?

View answer

Polymorphic association is a term used in discussions of Object-Relational Mapping with respect to the problem of representing in the relational database domain, a relationship from one class to multiple classes. In statically typed languages such as Java these multiple classes are subclasses of the same superclass.

What is the difference between load and get method in hibernate?

View answer

Session.load(): It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object. If no row found , it will throws an ObjectNotFoundException.

Is hibernate Sessionfactory Singleton?

View answer

SessionFactory is also thread safe so only one thread can execute at a time its code. The instance of sessionFactory is heavyweighted because it contains connection, hibernate configuration, mapping files, location path so if you create number of instance of sessionFactory then your code becomes very heavy.

What is the use of dialect in hibernate?

View answer

Dialect means “the variant of a language”. Hibernate, as we know, is database agnostic. It can work with different databases. However, databases have proprietary extensions/native SQL variations, and set/sub-set of SQL standard implementations. Therefore at some point hibernate has to use database specific SQL.

What is the use of Show_sql in hibernate?

View answer

Hibernate has build-in a function to enable the logging of all the generated SQL statements to the console. You can enable it by add a “show_sql” property in the Hibernate configuration file “ hibernate.cfg.xml “. This function is good for basic troubleshooting, and to see what’s Hibernate is doing behind.

Is Sessionfactory immutable?

View answer

The internal state of a SessionFactory is immutable. Most problems with concurrency occur due to sharing of objects with mutable state. Once the object is immutable, its internal state is setted on creation and cannot be changed. So many threads can access it concurrently and request for sessions.

Is Hibernate configuration file mandatory?

View answer

Basically you are setting all the required properties via your properties object so there is no real need to tell Hibernate to look for a hibernate.cfg.xml file which is exactly what the configure() method does. No, it’s not mandatory to use hibernate.cfg.xml. Just don’t use .configure().

What is meant by annotation in hibernate?

View answer

Hibernate annotations are the newest way to define mappings without the use of XML file. You can use annotations in addition to or as a replacement of XML mapping metadata. Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping.

What does hibernate.hbm2ddl.auto create means?

View answer

hibernate.hbm2ddl.auto. Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop , the database schema will be dropped when the SessionFactory is closed explicitly.

What is the use of projection in hibernate?

View answer

To put it simple, Hibernate Projections are used in order to query only a subset of the attributes of an entity or group of entities you’re querying with Criteria. You can also use Projections to specify distinct clauses and aggregate functions like max , sum and so on. Like modifying the select clause in an SQL query.

Can I disable first level cache in hibernate?

View answer

The scope of cache objects is of session. Once session is closed, cached objects are gone forever. First level cache is enabled by default and you can not disable it. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session.

What is the use of bag in hibernate?

View answer

Hibernate 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.

What is the use of Mappedby in hibernate?

View answer

With the mappedBy , you directly tell Hibernate/JPA that one table owns the relationship, and therefore it is stored as a column of that table. Without, the relationship is external and Hibernate/JPA need to create another table to store the relationship.

What is inverse true in hibernate?

View answer

The real meaning is that it defines which side is the parent or the relationship owner for the two entities (parent or child). Hence, inverse=”true” in a Hibernate mapping shows that this class (the one with this XML definition) is the relationship owner; while the other class is the child.

What is a bidirectional relationship?

View answer

Bidirectional Relationships. In a bidirectional relationship, each entity has a relationship field or property that refers to the other entity. Through the relationship field or property, an entity class’s code can access its related object.

What is JMX in Hybernate?

View answer

Java Management Extensions (JMX) is a Java technology that supplies tools for managing and monitoring applications, system objects, devices (such as printers) and service-oriented networks. Those resources are represented by objects called MBeans (for Managed Bean).

How to bind hibernate session factory to JNDI?

View answer

When binding the SessionFactory to JNDI, Hibernate will use the values of hibernate.jndi.url , hibernate.jndi.class to instantiate an initial context.

What are the fetching strategies in hibernate?

View answer

There are four fetching strategies

  1. fetch-“join” = Disable the lazy loading, always load all the collections and entities.

  2. fetch-“select” (default) = Lazy load all the collections and entities.

  3. batch-size=”N” = Fetching up to ‘N’ collections or entities, Not record.

  4. fetch-“subselect” = Group its collection into a sub select statement.

What are derived properties in hibernate?

View answer

In Hibernate a derived property (also called a calculated property) is a read-only property whose value is calculated at fetch time using SQL expressions.

What is version property in hibernate?

View answer

Theproperty (or @Version annotation) – We know that that Hibernate can provide optimistic locking through a version property on your persistent objects. Furthermore, the version property is automatically managed by Hibernate.

What does session lock () method do in hibernate?

View answer

The lock() method, with LockOptions.NONE, can be used to associate a detached object to a session and put the object back into a persistence context. On top is Hibernate code to reattach a detached object using a typical update method call. On the bottom is code to reattach a detached object using a lock method call.

What does evict do in hibernate?

View answer

evict() To detach the object from session cache, hibernate provides evict() method. After detaching the object from the session, any change to object will not be persisted. The associated objects will also be detached if the association is mapped with cascade=”evict”.

What is table per concrete class in hibernate?

View answer

When we use Table Per Concrete class in hibernate, tables are created per class. So there are no nullable values in the table. Disadvantage of this approach is that duplicate columns are created in the subclass tables.

What is light object mapping in hibernate?

View answer

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

The code is hidden from the business logic by implementing specific design patterns. In this Light Object Mapping in Hibernate is one of the valuable levels of ORM quality that approach for successful application which having less number of entities, or for common applications, Metadata and driven data models.

Advanced

Can you tell something about Table Per Class Strategy.

View answer

Table Per Class Strategy is another type of inheritance mapping strategy where each class in the hierarchy has a corresponding mapping database table. For example, the InterviewBitContractEmployee class details are stored in the interviewbit_contract_employee table and InterviewBitPermanentEmployee class details are stored in interviewbit_permanent_employee tables respectively. As the data is stored in different tables, there will be no need for a discriminator column as done in a single table strategy.

Hibernate provides @Inheritance annotation which takes strategy as the parameter. This is used for defining what strategy we would be using. By giving them value, InheritanceType.TABLE_PER_CLASS, it signifies that we are using a table per class strategy for mapping.

The code snippet will be as shown below:

InterviewBitEmployee class:

@Entity(name = "interviewbit_employee") @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @NoArgsConstructor @AllArgsConstructor public class InterviewBitEmployee { @Id @Column(name = "employee_id") private String employeeId; private String fullName; private String email; } InterviewBitContractEmployee class:

@Entity(name = "interviewbit_contract_employee") @Table(name = "interviewbit_contract_employee") @NoArgsConstructor @AllArgsConstructor public class InterviewBitContractEmployee extends InterviewBitEmployee { private LocalDate contractStartDate; private LocalDate contractEndDate; private String agencyName; } InterviewBitPermanentEmployee class:

@Entity(name = "interviewbit_permanent_employee") @Table(name = "interviewbit_permanent_employee") @NoArgsConstructor @AllArgsConstructor public class InterviewBitPermanentEmployee extends InterviewBitEmployee { private LocalDate workStartDate; private int numberOfLeaves; } Disadvantages:

  • This type of strategy offers less performance due to the need for additional joins to get the data.
  • This strategy is not supported by all JPA providers.
  • Ordering is tricky in some cases since it is done based on a class and later by the ordering criteria.