Hibernate N+1 Select Problem

Hibernate N + 1 Select Problem

The N + 1 Select problem is a performance issue in Hibernate. In this problem, a Java application makes N + 1 database calls (N = number of objects fetched). For example, if N= 2, the application makes 3 (N+1= 3) database calls.

Example

Let’s understand this problem with the help of an example. In this example, we are taking two POJO classes, Employee.java and Department.java. There exists a one-to-many association mapping between the two POJO classes. So that, one Department (Parent) can have many Employees (Child).

The Department and Employee classes are written below:

Department.java

import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="deptmnt")
public class Department {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="d_id")
private int did;
@Column(name="d_name")
private String dname;
@OneToMany(mappedBy="dep", cascade=CascadeType.PERSIST)
private List emp = new ArrayList();
public int getDid() {
return did;
}
public void setDid(int did) {
this.did = did;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public List getEmp() {
return emp;
}
public void setEmp(List emp) {
this.emp = emp;
}
} 

In the Department class, department id (did), department name (dname), and a List of employees are present.

Employee.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="employee")
public class Employee {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name="e_id")
private int eid;
@Column(name="e_name")
private String ename;
@ManyToOne
@JoinColumn(name="dept_id")
private Department dep;
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public Department getDep() {
return dep;
}
public void setDep(Department dep) {
this.dep = dep;
}
} 

In the Employee class, employee id (eid), employee name (ename), and an object of department class are present.

Following code is of the configuration file, which contains information about the database and the mapping classes.

hibernate.cfg.xml



org.hibernate.dialect.MySQL5Dialect
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/test2
root
root
create
true 
true



 

Now, we are going to create the main class, which stores the object of the POJO classes. Following code is of the App.java.

App.java

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class App 
{
public static void main( String[] args )
{
Configuration cfg= new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory fact= cfg.buildSessionFactory();
Session sess= fact.openSession();
sess.beginTransaction();
Employee e1 = new Employee();
e1.setEname("jyotika");
Employee e2= new Employee();
e2.setEname("shubham");
Employee e3= new Employee();
e3.setEname("nihal");
Employee e4= new Employee();
e4.setEname("neha");
Department d1= new Department();
d1.setDname("IT");
d1.getEmp().add(e1);
d1.getEmp().add(e2);
e1.setDep(d1);
e2.setDep(d1);
Department d2= new Department();
d2.setDname("Accounts");
d2.getEmp().add(e3);
d2.getEmp().add(e4);
e3.setDep(d2);
e4.setDep(d2);
sess.persist(d1);
sess.persist(d2);
List depart= sess.createQuery("From Department", Department.class).getResultList();
//List depart= sess.createQuery("From Department d JOIN fetch d.emp", Department.class).getResultList();
for (Department dep: depart){
System.out.println("Department details:::::");
System.out.println(dep.getDid()+"\t"+dep.getDname());
List<Employee> emp = dep.getEmp();
System.out.println("Employees details::::::");
for (Employee employee : emp) {
System.out.println(employee.getEid() + "\t" + employee.getEname());
}
}
sess.getTransaction().commit();
sess.close();
System.out.println("done");
}
} 

OUTPUT

The above output encountered the N+1 select problem, as separate select queries are executed for different objects. The first SELECT query selects the values of the Department (parent), and the rest two is for the Employee class (child).

The N+1 problem occurs due to the following code:

List depart= sess.createQuery("From Department", Department.class).getResultList();

To resolve the N+1 Select problem we can use the following approaches:

  1. HQL JOIN fetch

In place of the above code, we can use JOIN fetch to resolve the N+1 problem.

 List depart=sess.createQuery("From Department d JOIN fetch d.emp",Department.class)

.getResultList();

  • Criteria Query

We can also use Criteria query to resolve the N+1 select Problem. Following code shows the use of criteria query:

 CriteriaBuilder builder = sess.getCriteriaBuilder();
CriteriaQuery<Department> query = builder.createQuery(Department.class);
Root root = query.from(Department.class);
root.fetch("employees", JoinType.INNER); 

After resolving the N+1 problem, only one select query is executed for all the objects.

OUTPUT

Database Tables

Employee

Department


Related Topics

Hibernate Web Application Example

Web Application Example with Hibernate In this section, we create a hibernate web Application. Here we are using a JSP file for presentation. Example of creating a web application using hibernate index.jsp This page will show a...

2 minutes read.

Hibernate Inheritance Joined Table

In this inheritance strategy, mapping of the child class fields is done with the common fields of the parent class in a separate table. In other words, the common entities between the child...

3 minutes read.

Hibernate First-Level Cache

The first-level cache is related to the Session object. First level cache objects of one Session are not visible to the other Sessions, and all the cache data is lost when the Session...

2 minutes read.

Hibernate N+1 Select Problem

Hibernate N + 1 Select Problem The N + 1 Select problem is a performance issue in Hibernate. In this problem, a Java application makes N + 1 database calls (N = number...

4 minutes read.

Hibernate SessionFactory

Next → Hibernate SessionFactory A SessionFactory is an interface in Hibernate that create the instances of Session interface. It is a heavy weight object, and it is usually created during the application...

3 minutes read.

Dirty Checking in Hibernate

Dirty checking is an essential concept of Hibernate. The Dirty checking concept is used to keep track of the objects. It automatically detects whether an object is modified (or not) or wants to...

6 minutes read.

Hibernate first Example

Now we are going to create the first example in Hibernate. We will proceed step by step to develop the first Java application in Hibernate. The steps are listed below:- Create the POJO...

2 minutes read.

Hibernate save() vs persist()

Session.save() The session.save() method is used to save the transient object by assigning a generated value or using a current value of the identifier property. In other words, the save() method is used...

3 minutes read.

Hibernate Tutorial

What is Hibernate? Hibernate is an Object-Relational Mapping (ORM) tool which reduces the difficulty in the application development. Hibernate provides a framework that interacts with the data stored in the databases. It also uses...

3 minutes read.

Hibernate Session Interface

Hibernate Session Interface A Session is an interface between the Java application and the Hibernate. It is available in the org.hibernate.session package. It should not be kept open for a long time, as it...

4 minutes read.

Hibernate get() vs. load()

Hibernate methods, get() and load() both are provided by the Session interface and used to retrieve the objects from the database. Session.get() The session.get() method is used to fetch a persistent object of the...

2 minutes read.

Hibernate Many-to-One Mapping

Many-to-One Hibernate Mapping with Example A Many-to-One association mapping is the reverse of One-to-Many association mapping. For example, many (customers) are associated with one (vendor). In Hibernate, Many-to-One association mapping is applied from child class...

3 minutes read.

Hibernate Mapping

Hibernate Mapping Association- It means that two or more things are related to each other by some specific relation. In other words, it specifies how the objects are associated with each other. Hibernate mapping is one...

2 minutes read.

Hibernate GeneratedValue Strategies

Hibernate GeneratedValue Strategies Hibernate supports some generation strategies to generate a primary key in the database table. We can access the strategy with the help of @GeneratedValue annotation. @GeneratedValue The @GeneratedValue annotation specifies how to...

3 minutes read.

Hibernate One-to-One Mapping Example

One-to-One Hibernate Mapping In One-to-One association mapping, one object of a persistent class is related to one object of another persistent class. Here, we are going to create an example of one-to-one mapping using...

3 minutes read.

Hibernate Composite Primary Key

Hibernate Composite Primary Key A Composite Primary Key is a combination of one or more columns that forms a primary key. When a database table contains more than one primary key column, it is...

8 minutes read.

Lazy Loading in Hibernate

Lazy loading is a fetching technique used for all the entities in Hibernate. It decides whether to load a child class object while loading the parent class object. When we use association mapping...

3 minutes read.

Hibernate Web Application with Example

Let us create a hibernate web Application. Here we need JSP file for presentation. There are steps given below for the web app creation. index.jsp This page will show a registration form. It takes the...

2 minutes read.

Hibernate vs. JDBC

What is Hibernate? Hibernate is an Object-Relational Mapping (ORM) tool which reduces the difficulty in the application development. Hibernate provides a framework that interacts with the data stored in the databases. It also uses...

2 minutes read.

Hibernate Features

1. Lightweight Hibernate is a lightweight framework as it does not contains additional functionalities; it uses only those functionalities required for object-relational mapping. It is a lightweight framework because it uses persistent...

2 minutes read.