- Published on
Hibernate Interview Questions
- Authors
- Name
- Rahul Neelakantan
Hibernate is an open-source and lightweight ORM tool used to store, manipulate, and retrieve data from the database.
Table of Contents
- What is ORM?
- What are the core interfaces of Hibernate?
- List some of the databases supported by Hibernate?
- Mention some of the advantages of using ORM over JDBC?
- What is SessionFactory?
- What is Session?
- What are the states of the object in hibernate?
- How many types of association mapping are possible in hibernate?
- What is HQL?
- Explain about @Entity annotation in Hibernate?
- Explain about @Column annotation in Hibernate?
- Explain about @GeneratedValue annotation in Hibernate?
- What is the difference between Sequence and Identity in SQL?
- Explain about @Enumerated annotation in Hibernate?
- Explain about @Lob annotation in Hibernate?
- How many types of cache are present in Hibernate?
- Explain about First-Level Cache in Hibernate?
- Explain about Second-Level Cache in Hibernate?
- Explain about Query-Level Cache in Hibernate?
- Explain about Concurrency Strategies?
- Explain about Hibernate OGM?
- What is the purpose of Session.beginTransaction()?
- What is lazy loading?
- How would you define automatic dirty checking?
- Explain the different ways Hibernate manages concurrency?
- What is a hibernate configuration file?
- Hibernate Session is thread safe?
- What is the difference between Hibernate Session get() and load() method?
- What is the difference between Hibernate save() & persist() methods?
- Why should we not make Entity Class final?
- Can we execute native sql queries in hibernate?
- What is Hibernate Validator Framework?
- How transaction management works in Hibernate?
- What are the benefits of Named SQL Query?
- What is the benefit of Hibernate Criteria API?
- What is the difference between openSession and getCurrentSession?
- Explain more about Hibernate SessionFactory openStatelessSession?
- Is hibernate prone to SQL injection attack?
- What does session.lock() method in hibernate do?
- How to solve the N+1 SELECT problem in Hibernate?
- Explain about N+1 Select Problem?
- What is the dialect in hibernate?
- What is cascade in hibernate?
- What is meant by Light Object Mapping?
- What are the key components of a Hibernate configuration?
- Explain about mapping description files in Hibernate?
- Is hibernate.cfg.xml mandatory for Hibernate?
- How to add your configuration for Hibernate programmatically?
- Explain about Hibernate pool size?
- Explain difference between Join and Join Fetch?
- Explain differences between update and merge in Hibernate?
- Explain more about a different object with the same identifier that is already associated with a session?
- What do we mean by optimistic locking?
What is ORM?
ORM is an acronym for Object-Relational mapping. It is a programming strategy to map objects with the data stored in the database. It simplifies data creation, data manipulation, and data access.
What are the core interfaces of Hibernate?
The core interfaces of Hibernate framework are:
- Configuration
- SessionFactory
- Session
- Query
- Criteria
- Transaction
List some of the databases supported by Hibernate?
Some of the databases supported by Hibernate are:
- DB2
- MySQL
- Oracle
- Sybase SQL Server
- Informix Dynamic Server
- HSQL
- PostgreSQL
- FrontBase
Mention some of the advantages of using ORM over JDBC?
ORM has the following advantages over JDBC:
- Application development is fast.
- Management of transactions.
- Generates keys automatically.
- Details of SQL queries are hidden.
What is SessionFactory?
SessionFactory provides the instance of Session. It is immutable and thread-safe in nature.
Configuration object is used to create a SessionFactory object which in turn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated.
The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So, if you are using multiple databases, then you would have to create multiple SessionFactory objects.
What is Session?
It maintains a connection between the hibernate application and database.
Session provides methods to store, update, delete or fetch data from the database such as persist(), update(), delete(), load(), get() etc.
It is a factory of Query, Criteria and Transaction i.e. it provides factory methods to return these instances.
What are the states of the object in hibernate?
There are 3 states of the object (instance) in hibernate.
Transient: The object is in a transient state if it is just created but has no primary key (identifier) and not associated with a session.
Persistent: The object is in a persistent state if a session is open, and you just saved the instance in the database or retrieved the instance from the database.
Detached: The object is in a detached state if a session is closed. After the detached state, the object becomes a persistent state if you call the lock() or update() method.
How many types of association mapping are possible in hibernate?
- One to One
- One to Many
- Many to One
- Many to Many
What is HQL?
Hibernate Query Language is known as an object-oriented query language. It is like a structured query language (SQL).
The main advantage of HQL over SQL is:
- You don’t need to learn SQL
- Database independent
- Simple to write a query
Explain about @Entity annotation in Hibernate?
- It identifies a class as an entity class.
- It can be only defined on classes
- You can use the name attribute of the @Entity annotation to define the name of the entity
Explain about @Column annotation in Hibernate?
It is an optional annotation that enables you to customize the mapping between the entity attribute and the database column.
@Entity
public class Book {
@Column(name = "title")
private String title;
}
Explain about @GeneratedValue annotation in Hibernate?
If you annotate your primary key attribute with the @GeneratedValue annotation, you can use a database sequence by setting the strategy attribute to GenerationType.SEQUENCE. Or, if you want to use an auto-incremented database column to generate your primary key values, you need to set the strategy to GenerationType.IDENTITY.
The generator attribute of the @GeneratedValue annotation enables you to reference a custom generator. You can use it to customize a standard generator.
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
}
What is the difference between Sequence and Identity in SQL?
Sequence needs to be defined with following variables.
- Start value
- Increment by
- Min value
- Max value
- Cycle / No Cycle
Where as Identity only needs two variables, they are :-
- Seed value
- Increment by
Sequences do not generate duplicate values unless they have reached the maximum value and wrapped around to restart at the beginning, which is not the case for most sequences as the max value is set too high to use all the numbers.
Explain about @Enumerated annotation in Hibernate?
The @Enumerated annotation enables you to define how an enum attribute gets persisted in the database. By default, all JPA implementations map the ordinal value of the enum to a numeric database column.
Here AuthorStatus is the enumeration.
@Entity
public class Author {
@Enumerated(EnumType.STRING)
private AuthorStatus status;
}
Explain about @Lob annotation in Hibernate?
In Java, there is almost no limit to the size of a String or a byte[]. But that’s not the case for relational databases.
Using JPA’s @Lob annotation, you can map a BLOB to a byte[] and a CLOB to a String.
How many types of cache are present in Hibernate?
- First-level Cache
- Second-level Cache
- Query-level Cache
Explain about First-Level Cache in Hibernate?
The first-level cache is the Session cache and is a mandatory cache through which all requests must pass. The Session object keeps an object under its own power before committing it to the database.
If you issue multiple updates to an object, Hibernate tries to delay doing the update as long as possible to reduce the number of update SQL statements issued. If you close the session, all the objects being cached are lost and either persisted or updated in the database.
Explain about Second-Level Cache in Hibernate?
Second level cache is an optional cache. The second level cache can be configured on a per-class and per-collection basis and mainly responsible for caching objects across sessions. Any third-party cache can be used with Hibernate.
Explain about Query-Level Cache in Hibernate?
Hibernate also implements a cache for query resultsets that integrates closely with the second-level cache.
It holds 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.
Explain about Concurrency Strategies?
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.
- Transactional
- Read-write
- Nonstrict-read-write
- Read-only
Explain about Hibernate OGM?
Hibernate OGM (Object/Grid Mapper) provides Java Persistence (JPA) support for NoSQL solutions. It reuses Hibernate ORM’s engine but persists entities into a NoSQL datastore instead of a relational database.
What is the purpose of Session.beginTransaction()?
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.
What is lazy loading?
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.
How would you define automatic dirty checking?
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?
Hibernate has numerous ways of managing concurrency. They are as listed below:
- Automatic versioning
- Detached object
- Extended user sessions
What is a hibernate configuration file?
Hibernate configuration file contains database specific configurations and used to initialize SessionFactory. We provide database credentials or JNDI resource information in the hibernate configuration xml file. Some other important parts of a hibernate configuration file is Dialect information, so that hibernate knows the database type and mapping file or class details.
Hibernate Session is thread safe?
Hibernate Session object is not thread safe, every thread should get it’s own session instance and close it after it’s work is finished.
What is the difference between Hibernate Session get() and load() method?
Hibernate session comes with different methods to load data from the database. get and load are most used methods.
get() loads the data as soon as it’s called whereas load() returns a proxy object and loads data only when it’s actually required, so load() is better because it supports lazy loading. Also load() throws an exception when data is not found.
What is the difference between Hibernate save() & persist() methods?
Hibernate save can be used to save entities to the database. Problem with save() is that it can be invoked without a transaction and if we have mapping entities, then only the primary object gets saved causing data inconsistencies. Also save returns the generated id immediately.
Hibernate persist() is similar to save with a transaction. I feel it’s better than save because we can’t use it outside the boundary of transaction, so all the object mappings are preserved. Also persist doesn’t return the generated id immediately, so data persistence happens when needed.
Why should we not make Entity Class final?
Hibernate uses proxy classes for lazy loading of data, only when it’s needed. This is done by extending the entity bean; if the entity bean is final, then lazy loading will not be possible, hence low performance.
Can we execute native sql queries in hibernate?
Hibernate provides an option to execute native SQL queries through the use of SQLQuery objects.
What is Hibernate Validator Framework?
Data validation is an integral part of any application. Data validation occurs before persisting it, to make sure it follows the correct format.
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.CreditCardNumber;
import org.hibernate.validator.constraints.Email;
public class Employee {
@Min(value=1, groups=EmpIdCheck.class)
private int id;
@NotNull(message="Name cannot be null")
@Size(min=5, max=30)
private String name;
@Email
private String email;
@CreditCardNumber
private String creditCardNumber;
}
How transaction management works in Hibernate?
Transaction management is very easy in hibernate because most of the operations are not permitted outside of a transaction. So after getting the session from SessionFactory, we can call session beginTransaction() to start the transaction. This method returns the Transaction reference that we can use later on to either commit or rollback the transaction.
Overall hibernate transaction management is better than JDBC transaction management because we don’t need to rely on exceptions for rollback. Any exception thrown by session methods automatically rolls back the transaction.
What are the benefits of Named SQL Query?
Hibernate Named Query helps us in grouping queries at a central location rather than letting them scattered all over the code and 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, meaning once defined it can be used throughout the application.
However one of the major disadvantages of the Named query is that it’s hard to debug because we need to find out the location where it’s defined.
@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
}
)
What is the benefit of Hibernate Criteria API?
Hibernate provides Criteria API that is more object oriented for querying the database and getting results. We can’t use Criteria to run, update or delete queries or any DDL statements. It’s only used to fetch the results from the database using a more object oriented approach.
//Pagination Example
empList = session.createCriteria(Employee.class)
.addOrder(Order.desc("id"))
.setFirstResult(0)
.setMaxResults(2)
.list();
What is the difference between openSession and getCurrentSession?
getCurrentSession()
Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in a hibernate configuration file. Since this session object belongs to the hibernate context, we don’t need to close it. Once the session factory is closed, this session object gets closed.
openSession()
The Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in a multi-threaded environment.
Explain more about Hibernate SessionFactory openStatelessSession?
StatelessSession in Hibernate does not implement first-level cache and it doesn’t interact with any second-level cache. Since it’s stateless, it doesn’t implement transactional write-behind or automatic dirty checking or do cascading operations to associated entities.
Collections are also ignored by a stateless session. Operations performed via a stateless session bypass Hibernate’s event model and interceptors. It’s more like a normal JDBC connection and doesn’t provide any benefits that come from using hibernate framework.
However, stateless sessions can be a good fit in certain situations. For example where we are loading bulk data into a database and we don’t want a hibernate session to hold huge data in first-level cache memory.
Is hibernate prone to SQL injection attack?
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.
What does session.lock() method in hibernate do?
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.
How to solve the N+1 SELECT problem in Hibernate?
@Entity
public class Author {
@OneToMany(fetch=FetchType.LAZY, mappedBy="author")
@Fetch(FetchMode.SUBSELECT)
private List<Book> books;
}
If we were to iterate over each Author and print the books written by them, Hibernate would do 1 query for Authors and N queries for Books. To resolve this, we apply the following strategies in Hibernate.
- Pre-fetch the records in batches which helps us reduce the problem of N+1 to (N/K) + 1, where K refers to the size of the batch.
- Subselect the fetching strategy
- As a last resort, try to avoid or disable lazy loading altogether.
Explain about N+1 Select Problem?
Let’s say you have a collection of House objects and each House has a collection of People objects (also rows).
In other words, House → People is a 1-to-many relationship.
Now, let’s say you need to iterate through all the Houses, and for each one, print out a list of the Persons. The naive implementation would do the following:
SELECT * FROM House;
And then for each House we find number of persons**:**
SELECT * FROM Person WHERE HouseId = ?
In other words, you have one select for the House, and then N additional selects, where N is the total number of Houses.
Alternatively, one could get all Persons and perform the lookups in memory:
SELECT * FROM Person
This reduces the number of round-trips to the database from N+1 to 2.
Most ORM tools give you several ways to prevent N+1 selects.
What is the dialect in hibernate?
To connect hibernate applications with databases, we must specify the SQLDialect, which contains the mapping between java language data type and database data types. There are many dialect classes for defining the RDBMS.
Hibernate uses dialect configuration to know which database you are using so that it can switch to the database-specific SQL generator. Hibernate generates all your entity mappings and hibernate queries to Specific database queries and uses JDBC to execute them.
What is cascade in hibernate?
Cascading is about actions to be done based changes in one object propagating to other objects via an association.
Cascade is a convenient feature to save the lines of code needed to manage the state of the other side manually.
Please look at below example configuration for cascading.
<set name="stockDailyRecords" cascade="delete" table="stock_records">
<key>
<column name="stock_id" not-null="true" />
</key>
<one-to-many class="StockRecord" />
</set>
Query q = session.createQuery("from Stock where stock_id = :stock_id");
q.setParameter("stock_id", "999");
Stock stock = (Stock)q.list().get(0);
session.delete(stock);
What is meant by Light Object Mapping?
This means that the syntax is hidden from the business logic using specific design patterns. This is one of the valuable features of ORM quality and this Light Object Mapping approach can be successful in cases of applications where there are very few entities, or for applications having data models that are metadata-driven
What are the key components of a Hibernate configuration?
The configuration has 2 key components, namely:
Database Connection: This is handled by one or more configuration files.
Class Mapping setup: It helps in creating the connection between Java classes and database tables.
Explain about mapping description files in Hibernate?
These files have the *.hbm extension, which facilitates the mapping between database tables and Java class. They are used by Hibernate to configure functions. Whether to use mapping description files or not this entirely depends on business entities.
Is hibernate.cfg.xml mandatory for Hibernate?
No, it’s not mandatory to use hibernate.cfg.xml. Just don’t use .configure(). Hibernate will look for hibernate.cfg.xml if we use .configure()
How to add your configuration for Hibernate programmatically?
Hibernate provides a method for developers to add mapping files programmatically.
Just modify the default Hibernate SessionFactory class by passing your configuration file and resource files.
SessionFactory sessionFactory = new Configuration()
.configure("/com/codingjump/hibernate.cfg.xml")
.addResource("com/codingjump/Stock.hbm.xml")
.buildSessionFactory();
Explain about Hibernate pool size?
Limits the number of connections waiting in the Hibernate database connection pool.
connection.pool_size indicates the maximum number of pooled connections. So it is better to keep it at a logical count. It depends on your application and DB how much it can handle. 10 is a reasonable count that will typically be used as it is sufficient for most cases.
Explain difference between Join and Join Fetch?
Let’s say you’re joining an employee table with departments, also you’ve set mapping as FetchType.LAZY.
If you only use Join you are returning only the Employes for the Hibernate. In Join Fetch, you are returning the Employees and all Departments associated.
Explain differences between update and merge in Hibernate?
Hibernate handles persisting any changes to objects in the session when the session is flushed. update can fail if an instance of the object is already in the session. Merge should be used in that case. It merges the changes of the detached object with an object in the session, if it exists.
Update: if you are sure that the session does not contains an already persistent instance with the same identifier,then use update to save the data in hibernate
Merge: if you want to save your modifications at any time without knowing about the state of a session, then use merge() in hibernate.
Explain more about a different object with the same identifier that is already associated with a session?
Most probably it’s because the A objects are not referring to the same Java B object instance. They are referring to the same row in the database (i.e. the same primary key) but they’re different copies of it.
So what is happening is that the Hibernate session, which is managing the entities, would be keeping track of which Java object corresponds to the row with the same primary key.
One option would be to make sure that the Entities of objects A that refer to the same row are actually referring to the same object instance of B.
To resolve this you can use merge instead of update.
What do we mean by optimistic locking?
Normally when you look into optimistic locking, you also use a library like Hibernate or another JPA-Implementation with @Version support. While obviously, there is no point in adding a @Version annotation if you are not using a framework that supports this.
Optimistic Locking actually is no real DB-Lock. It just works by comparing the value of the version column. You don’t prevent other processes from accessing any data, so expect that you get OptimisticLockException
.
Optimistic Locking is no magic to merge conflicting changes; it will prevent processes from accidentally overwriting changes by another process.