Hibernate Interview Questions For Experienced
30. When is merge() method of the hibernate session useful?
It is mainly used when you want to save the changes back from your previously detached(outside scope of the Hibernate session) in the database. It generally used to update a detached object back to the persistence context(managed state).
In Hibernate, an object could be in one of these three states:
- transient
- persistent
- detached
So, if you want to merge the detached object you can use the merge() method to reattach it in a new session and compile it with changes to reflect it into the database.
Example:
To update existing Employee object which has been detached:-
// Detached object
Employee detachedEmployee = new Employee();
detachedEmployee.setId(1L);
detachedEmployee.setName("John Doe");
// You want to update the employee's name
detachedEmployee.setName("Jane Smith");
Session session = sessionFactory.openSession();
session.beginTransaction();
// Using merge to update the detachedEmployee
Employee updatedEmployee
= (Employee)session.merge(detachedEmployee);
session.getTransaction().commit();
session.close();
31. Does Hibernate support Native SQL Queries?
Yes, Hibernate supports Native SQL Queries which allows us to run SQL statements right against the database and we can use the createSQLQuery() method to use it in hibernate.
createSQLQuery(): It runs and recovers the results which returns a query object that is customised with parameters.
List of employee names and their salaries using custom SQL queries from database-
Session session = sessionFactory.openSession();
session.beginTransaction();
String sql = "SELECT name, salary FROM employees";
SQLQuery query = session.createSQLQuery(sql);
List<Object[]> results = query.list();
for (Object[] result : results) {
String name = (String)result[0];
BigDecimal salary = (BigDecimal)result[1];
System.out.println("Name: " + name
+ ", Salary: " + salary);
}
session.getTransaction().commit();
session.close();
32. What happens when the no-args constructor is absent in the Entity bean?
If no-args constructor is absent, instantiation of objects by hibernate can’t happen properly which leads to errors. No-args constructor in hibernate is an entity bean which is very essential as in instantiation of objects in hibernate done by its reflection of constructing java objects and reading data from the database.
Example without a no-args constructor:
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
// No no-args constructor
public Employee(String name) {
this.name = name;
}
}
In this example, when hibernate tries to instantiate Employee objects using reflection during data retrieval it will get an error as we can’t create objects without a no-args constructor.
Solution: Always add no-args constructor in your entity classes to get proper functioning with hibernate:
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name") private String name;
// No-args constructor
public Employee() {}
public Employee(String name) { this.name = name; }
}
By including no-args constructor, ‘Employee’ objects successfully get instantiated in hibernate when it requires reading data through the database.
33. Can we declare the Entity class final?
Yes, you can declare an entity or class as ‘final’ in hibernate but it has some complications as it can’t be subclassed which affects hibernate’s ability to perform tasks like runtime enhancements and proxy generation for lazy loading for certain features.
Entity class with ‘final’ modifier:
@Entity
@Table(name = "employees")
public final class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name") private String name;
}
34. Explain Query Cache?
The Query Cache in Hibernate is a mechanism designed to cache the results of database queries. It helps to optimise query performance by storing the query results in memory, reducing the need to repeatedly execute the same query against the database. When a cached query is executed again with the same parameters, hibernate can quickly retrieve the results from the cache, enhancing application responsiveness and reducing database load.
To executes query caching you should to do:
- By enabling second-level cache for session factory configurations.
- By enabling caching for a particular query using setCacheable(true)
35. How to solve the N+1 SELECT problem in Hibernate?
N+1 SELECT problem occurs in hibernate when calling the collections of entities takes a very large number of single SQL SELECT statements being executed and this majorly impacts performance as it runs the high number of database round-trips.
To solve this problem, we can use batch fetching and fetch joins techniques as: –
I. Batch Fetching
It can be used globally in hibernate configuration or at mapping level by using @BatchSize. It also fetches entities in batches by reducing the number of SELECT statements.
@Entity
@Table(name = "departments")
@BatchSize(size = 10) // Batch fetching for employees
public class Department {
}
II. Fetch Join
It allows to get both main and its related entities in a single result set. In HQL query by using JOIN FETCH syntax you can recover related entities in a single query.
String hql = "SELECT d FROM Department d JOIN FETCH d.employees WHERE d.id = :deptId";
Query query = session.createQuery(hql);
query.setParameter("deptId", 1L);
Department department = (Department)query.uniqueResult();
36. What is a Single Table Strategy?
In hibernate it’s one of the inheritance mapping strategies and mapped onto a single database table. Here all the attributes of the whole hierarchy stored in a single table and sidley discriminator column is used to separate between different subclasses.
Example:
Let’s say we have an inheritance hierarchy including base class Vehicle’ with two subclasses ‘Car’ and ‘Motorcycle’. By using Single Table Strategy all attributes of ‘Vehicle’, ‘Car’ and ‘Motorcycle’ feeded in a single database table also with a discriminator column to show the subclass type. To show the Single Table Strategy by using marked inheritance hierarchy:
// Entity 1
@Entity @DiscriminatorValue(“car”) public class Car extends Vehicle { private int numberOfDoors; }// Entity 2
@Entity @DiscriminatorValue(“motorcycle”) public class Motorcycle extends Vehicle { private boolean hasSideCar; }
37. What are the benefits of NamedQuery?
Named queries provide many benefits that support more maintainability, efficiency, and cleanliness of code. Some main advantages of using Named queries as:
- Separation of Concerns: It helps in increasing the code maintainability and readability by using SQL and HQL queries in the Java code and encourages clearer differences between application logic and data access.
- Code Reusability: It helps in reducing redundancy by reusing it across distinct parts of the application and makes it simple to apply changes to queries continuously by enhancing consistency.
- Performance Improvements: It helps in the repeated execution of queries by compiling at startup and by supplying needed performance improvements over ad-hoc queries each time.
- Maintainability: It helps when optimization efforts or schema changes need query adjustments. It can be managed centrally by making it simple to modify or update queries over your application.
Hibernate Interview Questions
Hibernate in Java is a powerful, high-performance Object/Relational Mapping (ORM) framework that greatly simplifies the development of Java applications to interact with databases. In this article, we present the top Hibernate Interview Questions that are commonly asked in interviews.
In this article, we will cover basic, intermediate, and advanced questions for candidates with years of experience in the form of Hibernate in Java Interview Questions.