logo
Product
Product Tour Science
Aptitude Tests Coding Tests Psychometric Tests Personality Tests
Campus Hiring Features Proctoring Enterprise
Test Library Questions Pricing
Resources
Blog Case studies Books Tools
About us
Login
Log In

Search test library by skills or roles
⌘ K
logo
Assessment Platform Aptitude Tests Coding Tests Psychometric Tests Personality Tests

TRY FOR FREE

Hibernate Interview Questions For Freshers
  1. What are the benefits of using Hibernate?
  2. What is ORM and how does it relate to Hibernate?
  3. How do you configure Hibernate with your application?
  4. What is a session in Hibernate and how is it used?
  5. What is a transaction in Hibernate and how does it work?
  6. What is the difference between a session and a transaction?
  7. What are the common mapping types in Hibernate?
  8. What is the difference between eager loading and lazy loading in Hibernate?
  9. How do you implement a one-to-many relationship in Hibernate?
  10. How do you implement a many-to-many relationship in Hibernate?
  11. How do you perform CRUD operations using Hibernate?
  12. How do you use HQL (Hibernate Query Language) to retrieve data?
  13. What are the different ways to retrieve data using Hibernate?
  14. How do you handle Hibernate exceptions?
  15. How do you handle optimistic and pessimistic locking in Hibernate?
  16. What is the purpose of a hibernate.cfg.xml file?
  17. How do you implement a one-to-one relationship in Hibernate?
  18. What is the difference between a session factory and a session in Hibernate?
  19. What is a cascade type in Hibernate and how is it used?
Hibernate Intermediate Interview Questions
  1. What is the difference between a stateless and stateful session in Hibernate?
  2. What is a Criteria API in Hibernate and how does it work?
  3. What is a second-level cache in Hibernate and how does it work?
  4. What is the difference between a first-level and a second-level cache in Hibernate?
  5. What is the difference between optimistic and pessimistic locking in Hibernate?
  6. How do you implement transactions in Hibernate?
  7. What are the best practices for using Hibernate in a multi-threaded environment?
  8. How do you implement inheritance in Hibernate?
  9. How do you use annotations in Hibernate?
  10. What is a composite key in Hibernate and how is it used?
  11. What are the different types of association mappings in Hibernate?
  12. What is a persistent object in Hibernate and how is it used?
  13. How do you use NamedQueries in Hibernate?
  14. What is the difference between a SQL query and a HQL query in Hibernate?
  15. What is the difference between a lazy and an eager fetch type?
  16. What is the difference between a proxy and a lazy loaded object in Hibernate?
  17. What is a connection pool in Hibernate and how does it work?
  18. How do you implement a many-to-many relationship with additional columns in Hibernate?
  19. What is a bytecode enhancement in Hibernate and how does it improve performance?
  20. How do you implement a composite primary key in Hibernate?
Hibernate Interview Questions For Experienced
  1. How do you optimize Hibernate performance?
  2. What is a detached object in Hibernate and how is it used?
  3. What are the best practices for using Hibernate with Spring?
  4. What is the difference between a one-to-one and a many-to-one relationship in Hibernate?
  5. What is a composite element in Hibernate and how is it used?
  6. What is the difference between a natural and a surrogate primary key in Hibernate?
  7. How do you implement a custom type in Hibernate?
  8. What is a custom dialect in Hibernate and how is it used?
  9. How do you use the Hibernate Validator to validate data?
  10. What is a filter in Hibernate and how does it work?
  11. What is the difference between an entity and a value object in Hibernate?
  12. How do you use the Hibernate Envers library for auditing purposes?
  13. What is a NamedNativeQuery in Hibernate and how does it work?
  14. What is the difference between a uni-directional and a bi-directional association mapping in Hibernate?
  15. How do you use the Hibernate Search library to implement full-text search?
  16. What is a metamodel in Hibernate and how is it used?
  17. What is the difference between a batch and a single insert in Hibernate?
  18. How do you use the Hibernate EntityManager API?
  19. What is a versioning strategy in Hibernate and how does it work?
  20. How do you use the Hibernate Interceptor API to intercept and modify SQL queries?


Interview Questions

Hibernate interview questions with detailed answers

Most important Hibernate interview questions for freshers, intermediate and experienced candidates. The important questions are categorized for quick browsing before the interview or to act as a detailed guide on different topics Hibernate interviewers look for.

Hibernate Online Test

Hibernate Interview Questions For Freshers

What are the benefits of using Hibernate?

View answer

Hide answer

Hibernate provides several benefits for Java developers, including:

  • Simplifying database interactions: By abstracting away low-level JDBC code, Hibernate simplifies database interactions and reduces boilerplate code.
  • Increased productivity: Hibernate's ORM capabilities reduce the amount of code developers need to write, increasing productivity.
  • Portability: Because Hibernate abstracts away database-specific SQL code, developers can more easily switch between databases without having to rewrite their application code.
  • Caching: Hibernate provides caching functionality, which can improve performance by reducing the number of database queries required.
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Employee emp = new Employee();
emp.setFirstName("John");
emp.setLastName("Doe");
session.save(emp);
tx.commit();
session.close();

Example of using Hibernate to persist an Employee object to a database.

What is ORM and how does it relate to Hibernate?

View answer

Hide answer

ORM (Object-Relational Mapping) is a programming technique that maps object-oriented models to relational database models, allowing developers to work with relational databases using object-oriented programming concepts. Hibernate is an ORM framework that provides a mapping between Java classes and database tables, allowing developers to interact with the database using objects.

@Entity
@Table(name = "employees")
public class Employee {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;
   private String firstName;
   private String lastName;
   // getters and setters
}

Example of an annotated Java class in Hibernate, used for mapping to a database table.

How do you configure Hibernate with your application?

View answer

Hide answer

To configure Hibernate with your application, you need to define a configuration file or use annotations to map Java classes to database tables. You also need to create a SessionFactory object, which is used to create Session objects to interact with the database. The configuration file can include information about the database connection, mapping files or annotations, and other settings.

<!-- Hibernate configuration file -->
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">password</property>
    <mapping class="com.example.Employee"/>
  </session-factory>
</hibernate-configuration>

Example of a Hibernate configuration file that specifies the database connection information and mapping for the Employee class.

What is a session in Hibernate and how is it used?

View answer

Hide answer

In Hibernate, a session is a lightweight object used to interact with the database. It provides methods for creating, reading, updating, and deleting persistent objects, as well as querying the database. A session is created from a SessionFactory object and should be used within a transaction.

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Employee emp = session.get(Employee.class, 1L);
emp.setLastName("Smith");
session.update(emp);
tx.commit();
session.close();

Example of using a session to retrieve an Employee object with ID 1, update its last name, and save the changes to the database.

What is a transaction in Hibernate and how does it work?

View answer

Hide answer

In Hibernate, a transaction is a sequence of operations that are executed as a single unit of work. Transactions ensure the consistency and integrity of the data by allowing for atomic, isolated changes to the database. Transactions are typically initiated by beginning a new transaction, performing one or more database operations within the transaction, and then committing the transaction to make the changes permanent. If an error occurs during the transaction, it can be rolled back to restore the previous state of the database.

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Employee emp = new Employee();
emp.setFirstName("John");
emp.setLastName("Doe");
session.save(emp);
tx.commit();
session.close();

Example of using a transaction to persist a new Employee object to the database. The transaction is committed to make the changes permanent.

What is the difference between a session and a transaction?

View answer

Hide answer

In Hibernate, a session is an object used to interact with the database and provides methods for creating, reading, updating, and deleting persistent objects. A transaction is a sequence of operations that are executed as a single unit of work and ensure the consistency and integrity of the data. A session is typically used within a transaction to perform database operations, and the transaction is committed to make the changes permanent.

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Employee emp = new Employee();
emp.setFirstName("John");
emp.setLastName("Doe");
session.save(emp);
tx.commit();
session.close();

Example of using a session to persist a new Employee object to the database within a transaction. The transaction is committed to make the changes permanent.

What are the common mapping types in Hibernate?

View answer

Hide answer

In Hibernate, the common mapping types are:

  • @Id: Specifies the primary key of an entity.
  • @GeneratedValue: Specifies the strategy for generating unique primary keys.
  • @Column: Specifies the mapping between a Java class attribute and a database column.
  • @ManyToOne/@OneToMany: Specifies a many-to-one or one-to-many relationship between two entities.
  • @OneToOne/@ManyToMany: Specifies a one-to-one or many-to-many relationship between two entities.
@Entity
@Table(name = "employees")
public class Employee {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;
   @Column(name = "first_name")
   private String firstName;
   @Column(name = "last_name")
   private String lastName;
   @ManyToOne
   @JoinColumn(name = "department_id")
   private Department department;
   // getters and setters
}

@Entity
@Table(name = "departments")
public class Department {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;
   @Column(name = "name")
   private String name;
   @OneToMany(mappedBy = "department")
   private List<Employee> employees;
   // getters and setters
}

Example of using mapping annotations in Hibernate to specify the primary key, column names, and relationships between Employee and Department entities.

What is the difference between eager loading and lazy loading in Hibernate?

View answer

Hide answer

In Hibernate, eager loading fetches all associated entities immediately when the parent entity is loaded from the database, while lazy loading loads the associated entities only when they are actually needed.

Eager loading can result in more efficient querying of the database, as all necessary data is retrieved in a single query, but it can also cause performance issues and waste resources if unnecessary data is retrieved. Lazy loading can improve performance by reducing the amount of data that needs to be retrieved from the database, but it can also result in additional database queries if the associated entities are accessed later.

@Entity
@Table(name = "departments")
public class Department {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;
   @Column(name = "name")
   private String name;
   @OneToMany(mappedBy = "department", fetch = FetchType.LAZY)
   private List<Employee> employees;
   // getters and setters
}

Example of using lazy loading in Hibernate to load the employees associated with a Department entity only when they are actually needed.

How do you implement a one-to-many relationship in Hibernate?

View answer

Hide answer

To implement a one-to-many relationship in Hibernate, you can use the @OneToMany annotation on the parent entity to specify the mapping. The @JoinColumn annotation can be used on the child entity to specify the foreign key column.

@Entity
@Table(name = "departments")
public class Department {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;
   @Column(name = "name")
   private String name;
   @OneToMany(mappedBy = "department")
   private List<Employee> employees;
   // getters and setters
}

@Entity
@Table(name = "employees")
public class Employee {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;
   @Column(name = "first_name")
   private String firstName;
   @Column(name = "last_name")
   private String lastName;
   @ManyToOne
   @JoinColumn(name = "department_id")
   private Department department;
   // getters and setters
}

Example of implementing a one-to-many relationship between Department and Employee entities in Hibernate. A department can have multiple employees, so a one-to-many relationship is established between them using the @OneToMany annotation on the Department entity and the @ManyToOne annotation on the Employee entity. The @JoinColumn annotation is used on the Employee entity to specify the foreign key column.

How do you implement a many-to-many relationship in Hibernate?

View answer

Hide answer

To implement a many-to-many relationship in Hibernate, you can use the @ManyToMany annotation on both entities involved in the relationship. You will also need to specify a join table using the @JoinTable annotation.

@Entity
@Table(name = "students")
public class Student {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;
   @Column(name = "name")
   private String name;
   @ManyToMany
   @JoinTable(name = "enrollments",
         joinColumns = @JoinColumn(name = "student_id"),
         inverseJoinColumns = @JoinColumn(name = "course_id"))
   private List<Course> courses;
   // getters and setters
}

@Entity
@Table(name = "courses")
public class Course {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;
   @Column(name = "name")
   private String name;
   @ManyToMany(mappedBy = "courses")
   private List<Student> students;
   // getters and setters
}

Example of implementing a many-to-many relationship between Student and Course entities in Hibernate. A student can enroll in multiple courses, and a course can have multiple students, so a many-to-many relationship is established between them using the @ManyToMany annotation on both entities. The @JoinTable annotation is used to specify the join table, and the mappedBy attribute is used on the Course entity to specify the owning side of the relationship.

How do you perform CRUD operations using Hibernate?

View answer

Hide answer

To perform CRUD operations using Hibernate, you can use the Session object provided by Hibernate. Here are some examples:

Create

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Employee employee = new Employee();
employee.setFirstName("John");
employee.setLastName("Doe");
session.save(employee);
transaction.commit();
session.close();

Read

Session session = sessionFactory.openSession();
Employee employee = session.get(Employee.class, 1L);
session.close();

Update

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Employee employee = session.get(Employee.class, 1L);
employee.setLastName("Smith");
session.update(employee);
transaction.commit();
session.close();

Delete

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Employee employee = session.get(Employee.class, 1L);
session.delete(employee);
transaction.commit();
session.close();

Example of performing CRUD operations using Hibernate. To create a new Employee entity, we create a new instance of the Employee class and call the save() method on the Session object. To read an existing Employee entity, we call the get() method on the Session object with the primary key value. To update an existing Employee entity, we call the update() method on the Session object with the modified entity. To delete an existing Employee entity, we call the delete() method on the Session object with the entity to be deleted.

How do you use HQL (Hibernate Query Language) to retrieve data?

View answer

Hide answer

To use HQL (Hibernate Query Language) to retrieve data, you can create a query using the createQuery() method of the Session object and specify the HQL statement. Here is an example:

Session session = sessionFactory.openSession();
String hql = "FROM Employee WHERE department=:department";
Query<Employee> query = session.createQuery(hql, Employee.class);
query.setParameter("department", "IT");
List<Employee> employees = query.list();
session.close();

In this example, we create a HQL query to retrieve all employees from the Employee table where the department is "IT". We use a named parameter department to avoid SQL injection and set its value using the setParameter() method. Finally, we execute the query using the list() method and get the result as a List of Employee objects.

What are the different ways to retrieve data using Hibernate?

View answer

Hide answer

There are several ways to retrieve data using Hibernate:

  1. Session.get() - Retrieve a persistent object by its identifier.
Session session = sessionFactory.openSession();
Employee employee = session.get(Employee.class, 1L);
session.close();
  1. Session.load() - Load a persistent object by its identifier. This method returns a proxy object and may throw an exception if the object does not exist.
Session session = sessionFactory.openSession();
Employee employee = session.load(Employee.class, 1L);
session.close();
  1. HQL (Hibernate Query Language) - Use HQL to retrieve objects using a SQL-like query language.
Session session = sessionFactory.openSession();
String hql = "FROM Employee WHERE department=:department";
Query<Employee> query = session.createQuery(hql, Employee.class);
query.setParameter("department", "IT");
List<Employee> employees = query.list();
session.close();
  1. Criteria API - Use the Criteria API to build type-safe queries programmatically.
Session session = sessionFactory.openSession();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Employee> criteria = builder.createQuery(Employee.class);
Root<Employee> root = criteria.from(Employee.class);
criteria.select(root).where(builder.equal(root.get("department"), "IT"));
List<Employee> employees = session.createQuery(criteria).list();
session.close();

All of these methods can be used to retrieve data in Hibernate, and the choice of which method to use will depend on the requirements of the application.

How do you handle Hibernate exceptions?

View answer

Hide answer

Hibernate throws many different types of exceptions, including HibernateException, ObjectNotFoundException, NonUniqueObjectException, and StaleObjectStateException. These exceptions can be handled using try-catch blocks in Java.

try {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    // perform database operation
    tx.commit();
    session.close();
} catch (HibernateException e) {
    // handle the exception
    e.printStackTrace();
}

It is important to handle Hibernate exceptions carefully, as they can indicate issues with the database connection or data integrity problems. In addition to catching exceptions, it is a good practice to log the exceptions using a logging framework like Log4j or SLF4J to aid in debugging.

How do you handle optimistic and pessimistic locking in Hibernate?

View answer

Hide answer

Optimistic locking and pessimistic locking are two approaches to handle concurrent access to the same data by multiple users in Hibernate.

In optimistic locking, Hibernate checks if the record has been changed since it was last read by the user. If changes are detected, an OptimisticLockException is thrown.

try {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    // perform select and update operation
    tx.commit();
    session.close();
} catch (OptimisticLockException e) {
    // handle the optimistic locking exception
    e.printStackTrace();
}

In pessimistic locking, Hibernate locks the data record while it is being updated to prevent other users from accessing it until the update is complete.

try {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    // perform select and update operation with pessimistic lock
    tx.commit();
    session.close();
} catch (HibernateException e) {
    // handle the exception
    e.printStackTrace();
}

The choice between optimistic and pessimistic locking depends on the application's requirements and the potential for concurrent access to the data.

What is the purpose of a hibernate.cfg.xml file?

View answer

Hide answer

The hibernate.cfg.xml file is the configuration file for Hibernate that contains settings such as the database connection details, dialect, mapping files, and other configuration options. It is typically located in the classpath of the application.

Here is an example of a hibernate.cfg.xml file:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">password</property>
    <mapping class="com.example.model.User"/>
  </session-factory>
</hibernate-configuration>

This configuration file is loaded by the SessionFactory to establish a connection with the database and configure Hibernate.

How do you implement a one-to-one relationship in Hibernate?

View answer

Hide answer

To implement a one-to-one relationship in Hibernate, you can use either the @OneToOne or @PrimaryKeyJoinColumn annotation.

Using @OneToOne:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
    private Address address;
    //...
}

@Entity
public class Address {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String street;
    private String city;
    private String state;
    private String zip;

    @OneToOne
    @JoinColumn(name = "user_id")
    private User user;
    //...
}

Using @PrimaryKeyJoinColumn:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
    private Address address;
    //...
}

@Entity
public class Address {
    @Id
    private Long id;
    private String street;
    private String city;
    private String state;
    private String zip;

    @MapsId
    @OneToOne
    @JoinColumn(name = "id")
    private User user;
    //...
}

In both cases, the @OneToOne annotation specifies the relationship between the two entities. The mappedBy attribute indicates that the relationship is bidirectional and that the User entity is not the owner of the relationship. The @JoinColumn annotation specifies the foreign key column used to map the relationship.

The difference between the two approaches is that the first approach uses a separate primary key column in the Address table, while the second approach uses the primary key column of the User table as the foreign key in the Address table.

What is the difference between a session factory and a session in Hibernate?

View answer

Hide answer

In Hibernate, a SessionFactory is a thread-safe and immutable cache of compiled mappings for a database, while a Session represents a single-threaded unit of work with a database. The SessionFactory is created once during application startup, whereas the Session is created as needed and is used to interact with the database for a particular unit of work. The SessionFactory is responsible for creating new Sessions as needed, and the Sessions interact with the database to perform CRUD operations and other database-related tasks.

What is a cascade type in Hibernate and how is it used?

View answer

Hide answer

In Hibernate, a cascade type defines how operations performed on an entity are propagated to its associated entities. For example, if a parent entity is deleted, its child entities can also be deleted automatically if a cascade type of "delete" is defined for the association between the parent and child entities. Cascade types can be defined on one-to-one, one-to-many, many-to-one, and many-to-many associations. Here is an example of defining cascade types in Hibernate:

@Entity
public class Parent {
    @OneToMany(mappedBy="parent", cascade=CascadeType.ALL)
    private Set<Child> children;
    // ...
}

@Entity
public class Child {
    @ManyToOne
    @JoinColumn(name="parent_id")
    private Parent parent;
    // ...
}

In this example, the "cascade=CascadeType.ALL" attribute on the "children" field in the Parent entity specifies that any operations performed on the Parent entity (e.g. save, update, delete) should also be cascaded to the associated Child entities.

Hibernate Intermediate Interview Questions

What is the difference between a stateless and stateful session in Hibernate?

View answer

Hide answer

In Hibernate, a stateful session is associated with a single database transaction and maintains a first-level cache, while a stateless session is not associated with any transaction and does not maintain any cache. Stateful sessions are suitable for short-lived transactions where multiple operations are required, while stateless sessions are suitable for long-lived transactions that do not require any caching. Here's an example of a stateful session:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

// Perform database operations using session

tx.commit();
session.close();

And here's an example of a stateless session:

StatelessSession session = sessionFactory.openStatelessSession();

// Perform database operations using session

session.close();

What is a Criteria API in Hibernate and how does it work?

View answer

Hide answer

The Criteria API is a programmatic and type-safe way to create queries in Hibernate. It is an alternative to HQL and SQL and allows developers to create queries using Java objects and method calls, making it easier to write and maintain queries. The Criteria API creates a Criteria object that can be used to specify the query parameters and restrictions. Here is an example of how to use the Criteria API to retrieve all entities of a given class:

CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Entity> cq = cb.createQuery(Entity.class);
Root<Entity> root = cq.from(Entity.class);
cq.select(root);
List<Entity> entities = session.createQuery(cq).getResultList();

What is a second-level cache in Hibernate and how does it work?

View answer

Hide answer

A second-level cache in Hibernate is used to improve application performance by reducing the number of database queries needed to retrieve data. It is a shared cache between multiple sessions and provides a way to cache objects and queries that are commonly used in the application. The second-level cache stores objects in memory, so that they can be retrieved quickly without having to go to the database. Hibernate automatically manages the second-level cache and provides configuration options to customize its behavior. Here's an example of configuring the second-level cache in Hibernate:

<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</property>

What is the difference between a first-level and a second-level cache in Hibernate?

View answer

Hide answer

The first-level cache in Hibernate is the session-level cache which stores the objects loaded in a particular session. It is enabled by default and improves performance by reducing the number of SQL queries. The second-level cache is the application-level cache which stores the objects loaded in multiple sessions. It requires configuration and can be shared across multiple sessions. It reduces the database hit and improves the performance of an application.

What is the difference between optimistic and pessimistic locking in Hibernate?

View answer

Hide answer

Optimistic locking and pessimistic locking are concurrency control mechanisms used in Hibernate to ensure data consistency in a multi-user environment.

Optimistic locking assumes that concurrent updates are infrequent, so it allows multiple transactions to read and modify data simultaneously. When a transaction tries to commit changes, Hibernate checks if the data has been modified by another transaction. If the data has not been modified, the transaction can commit changes. Otherwise, the transaction must be rolled back.

Pessimistic locking assumes that concurrent updates are frequent, so it locks the data to prevent other transactions from modifying it. There are different types of pessimistic locks, such as shared locks and exclusive locks, depending on the level of access granted to other transactions. When a transaction acquires a pessimistic lock, other transactions must wait until the lock is released before they can access the data.

How do you implement transactions in Hibernate?

View answer

Hide answer

Transactions can be implemented in Hibernate by starting a transaction, performing database operations within the transaction, and then either committing or rolling back the transaction. Here is an example of starting a transaction in Hibernate:

Session session = sessionFactory.openSession();
Transaction tx = null;

try {
    tx = session.beginTransaction();
    // perform database operations within the transaction
    session.save(entity);
    tx.commit();
} catch (Exception e) {
    if (tx != null) {
        tx.rollback();
    }
} finally {
    session.close();
}

In the above example, sessionFactory is an instance of SessionFactory and entity is the object being saved to the database. By calling session.beginTransaction(), a new transaction is started, and session.save(entity) is performed within the transaction. If no exceptions are thrown, the transaction is committed using tx.commit(). If an exception is thrown, the transaction is rolled back using tx.rollback(). Finally, the session is closed.

What are the best practices for using Hibernate in a multi-threaded environment?

View answer

Hide answer

When using Hibernate in a multi-threaded environment, it is important to follow some best practices:

  1. Use a separate session per thread.
  2. Use connection pooling to manage database connections.
  3. Use optimistic locking to avoid data conflicts.
  4. Avoid lazy loading if possible to reduce the number of database calls.
  5. Use the appropriate transaction isolation level based on your needs.
  6. Use thread-safe entities to avoid data corruption.
  7. Avoid using global variables to store session factory or session objects.
  8. Use appropriate synchronization mechanisms when accessing shared resources.

Here's an example of how to use a separate session per thread in a multi-threaded environment:

public class MyThread implements Runnable {
    private SessionFactory sessionFactory;

    public MyThread(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void run() {
        Session session = sessionFactory.openSession();
        Transaction tx = null;

        try {
            tx = session.beginTransaction();

            // Perform database operations

            tx.commit();
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
        } finally {
            session.close();
        }
    }
}

// Create thread pool and execute threads
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
    executorService.execute(new MyThread(sessionFactory));
}
executorService.shutdown();

How do you implement inheritance in Hibernate?

View answer

Hide answer

In Hibernate, inheritance can be implemented using three approaches: Single Table, Table per Class, and Joined Table.

  • Single Table: All classes are mapped to a single table, which contains all the columns of all the classes.
  • Table per Class: Each class is mapped to its own table.
  • Joined Table: Each class is mapped to its own table, and a separate table is created to store common fields.

To implement inheritance, you can use the @Inheritance annotation and specify the strategy. For example, to use the single table strategy, you can annotate the superclass with @Inheritance(strategy=InheritanceType.SINGLE_TABLE).

How do you use annotations in Hibernate?

View answer

Hide answer

Annotations in Hibernate are used to define the mapping between Java classes and database tables without the need for XML configuration files. Annotations can be used to define entity classes, primary keys, relationships between entities, and more. To use annotations in Hibernate, you need to add the necessary Hibernate annotations to your Java classes and configure Hibernate to use the annotations in your Hibernate configuration file. Here's an example of using the @Entity annotation to define an entity class in Hibernate:

@Entity
@Table(name = "employees")
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

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

    @Column(name = "salary")
    private BigDecimal salary;

    // Getters and setters
}

What is a composite key in Hibernate and how is it used?

View answer

Hide answer

A composite key in Hibernate is a primary key that is made up of two or more columns instead of a single column. It is used when a table has more than one column that uniquely identifies a row. A composite key is defined using the @Embeddable and @EmbeddedId annotations in Hibernate. The @Embeddable annotation is used to specify a class whose instances are stored as components of an entity, and the @EmbeddedId annotation is used to specify the composite key class as the identifier of the entity. Here's an example:

@Embeddable
public class EmployeeId implements Serializable {
    private int empId;
    private String deptName;
    // getters and setters
}

@Entity
public class Employee {
    @EmbeddedId
    private EmployeeId empId;
    // other fields and methods
}

What are the different types of association mappings in Hibernate?

View answer

Hide answer

The different types of association mappings in Hibernate are:

  • One-to-One: Uses @OneToOne annotation to map a relationship between two entities where each instance of one entity is associated with only one instance of another entity.
  • One-to-Many: Uses @OneToMany annotation to map a relationship between two entities where each instance of one entity is associated with multiple instances of another entity.
  • Many-to-One: Uses @ManyToOne annotation to map a relationship between two entities where multiple instances of one entity are associated with only one instance of another entity.
  • Many-to-Many: Uses @ManyToMany annotation to map a relationship between two entities where multiple instances of one entity are associated with multiple instances of another entity.

What is a persistent object in Hibernate and how is it used?

View answer

Hide answer

A persistent object in Hibernate is an object that is associated with a database table and has a corresponding row in that table. Once an object is made persistent, any changes made to it will be tracked by Hibernate and will be automatically synchronized with the database when a transaction is committed. Persistent objects are managed by Hibernate's session and can be retrieved, updated, and deleted using Hibernate's APIs. The state of the persistent object is maintained across different transactions until the session is closed. To make an object persistent in Hibernate, it needs to be saved using the save or saveOrUpdate method.

How do you use NamedQueries in Hibernate?

View answer

Hide answer

NamedQueries in Hibernate provide a way to define and execute named queries that are defined in the Hibernate mapping files or through annotations. To use NamedQueries, you need to define the queries in the entity class or in the Hibernate mapping file and give them a name. Once defined, you can use the session's getNamedQuery() method to retrieve the named query and execute it. Here is an example:

@Entity
@NamedQuery(
    name = "findEmployeeByName",
    query = "SELECT e FROM Employee e WHERE e.name = :name"
)
public class Employee {
    // ...
}

// Usage
Query query = session.getNamedQuery("findEmployeeByName");
query.setParameter("name", "John Doe");
List<Employee> employees = query.list();

What is the difference between a SQL query and a HQL query in Hibernate?

View answer

Hide answer

A SQL query is written in the SQL language, while a HQL query is written in the Hibernate Query Language. HQL is a higher-level abstraction of SQL and is specific to Hibernate. SQL queries are written for a specific database, while HQL queries are database-independent. HQL queries operate on entities and their properties, while SQL queries operate on tables and columns. HQL queries can take advantage of Hibernate's caching and lazy-loading features, while SQL queries cannot.

What is the difference between a lazy and an eager fetch type?

View answer

Hide answer

In Hibernate, a lazy fetch type means that associated entities are not loaded from the database until they are explicitly requested, while an eager fetch type means that associated entities are loaded immediately with their parent entity. Lazy fetching can improve performance by avoiding unnecessary database queries, while eager fetching can be useful when the associated entities are always needed.

Here is an example of specifying the fetch type for a @ManyToOne association:

@Entity
public class Order {
    // ...

    @ManyToOne(fetch = FetchType.LAZY)
    private Customer customer;

    // ...
}

In this example, the customer association is set to use lazy fetching, so the associated Customer entity will not be loaded from the database until it is explicitly accessed.

What is the difference between a proxy and a lazy loaded object in Hibernate?

View answer

Hide answer

In Hibernate, a proxy is a placeholder object that is created instead of an actual entity when a reference to that entity is requested. The purpose of the proxy is to avoid fetching the actual entity from the database until it is actually needed, in order to improve performance. A lazy loaded object, on the other hand, is an actual entity that is loaded from the database only when its properties are accessed. The main difference between the two is that a proxy is a lightweight object that doesn't actually load the entity, while a lazy loaded object is the actual entity that is loaded on demand.

What is a connection pool in Hibernate and how does it work?

View answer

Hide answer

A connection pool in Hibernate is a cache of database connections that are created and managed by the application server. It reduces the overhead of creating and closing database connections, thereby improving performance. A connection pool maintains a set of database connections that are available for use by applications, and returns them to the pool when they are no longer needed. Hibernate supports various third-party connection pool providers such as C3P0, HikariCP, and Apache DBCP. The connection pool is configured in the Hibernate configuration file or through Java code.

How do you implement a many-to-many relationship with additional columns in Hibernate?

View answer

Hide answer

To implement a many-to-many relationship with additional columns in Hibernate, you need to create an entity to represent the association table, with foreign keys to the entities involved in the relationship and any additional columns. Then, you can use @ManyToMany annotations on the corresponding properties of each entity, specifying the association table entity as the joinTable and mapping the foreign keys to the primary keys of the entities. Here's an example:

@Entity
public class Book {
    @Id
    private Long id;

    @ManyToMany
    @JoinTable(name = "book_author",
               joinColumns = @JoinColumn(name = "book_id"),
               inverseJoinColumns = @JoinColumn(name = "author_id"))
    private List<Author> authors;

    // ...
}

@Entity
public class Author {
    @Id
    private Long id;

    @ManyToMany(mappedBy = "authors")
    private List<Book> books;

    // ...
}

@Entity
public class BookAuthor {
    @Id
    private Long id;

    @ManyToOne
    @JoinColumn(name = "book_id")
    private Book book;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;

    private Integer royalties;

    // ...
}

What is a bytecode enhancement in Hibernate and how does it improve performance?

View answer

Hide answer

Bytecode enhancement in Hibernate is a process of modifying the entity classes at compile-time or load-time to add extra functionality for better performance. It involves adding optimized bytecode to the entity classes, such as lazy loading, dirty checking, and caching. This enhancement helps to reduce the number of database queries and improves the overall performance of the application. For example, the bytecode enhancement of a lazy-loaded attribute will load the attribute from the database only when it is accessed for the first time, instead of loading all attributes of an entity at once.

How do you implement a composite primary key in Hibernate?

View answer

Hide answer

To implement a composite primary key in Hibernate, you can define a new class that represents the composite key and use the @EmbeddedId annotation on the entity to associate it with the composite key. The composite key class should have the @Embeddable annotation, and its properties should be annotated with @Column to map them to the columns in the table. Here's an example:

@Embeddable
public class CompositeKey implements Serializable {

    @Column(name = "id1")
    private Long id1;

    @Column(name = "id2")
    private Long id2;

    // getters and setters
}

@Entity
@Table(name = "my_table")
public class MyEntity {

    @EmbeddedId
    private CompositeKey compositeKey;

    // other properties and methods
}

Hibernate Interview Questions For Experienced

How do you optimize Hibernate performance?

View answer

Hide answer

There are several ways to optimize Hibernate performance:

  • Use caching (first-level cache, second-level cache, query cache) to reduce database hits.
  • Use lazy loading to reduce the number of objects loaded into memory.
  • Use batch processing to reduce database round trips.
  • Avoid unnecessary joins and fetch only required data.
  • Use appropriate indexing to speed up queries.
  • Use connection pooling to reuse database connections.
  • Tune Hibernate configuration properties for optimal performance.

What is a detached object in Hibernate and how is it used?

View answer

Hide answer

In Hibernate, a detached object is an object that was previously associated with a Hibernate session but is no longer associated with any session. Detached objects can be modified and reattached to a session for later persistence. This is useful when working with long-running transactions or when passing objects between different layers of an application. To reattach a detached object to a session, you can use the update() or merge() method. For example:

// Load an object and then detach it
MyObject obj = session.load(MyObject.class, id);
session.evict(obj);

// Modify the object
obj.setName("New Name");

// Reattach the object to a session
session.update(obj);

What are the best practices for using Hibernate with Spring?

View answer

Hide answer

When using Hibernate with Spring, it is best to use Spring's declarative transaction management to manage transactions. This involves annotating the service layer methods with **@Transactional**to enable transaction management. Additionally, it is recommended to use Spring's LocalSessionFactoryBean to create the SessionFactory bean, and to use dependency injection to inject the SessionFactory into the DAO classes. Finally, it is recommended to use Spring's caching features for second-level caching, and to avoid using Hibernate's built-in connection pooling in favor of Spring's connection pooling capabilities.

What is the difference between a one-to-one and a many-to-one relationship in Hibernate?

View answer

Hide answer

In Hibernate, a one-to-one relationship indicates that one entity is associated with another entity using a shared primary key. In contrast, a many-to-one relationship indicates that many instances of one entity can be associated with one instance of another entity using a foreign key. The difference between them is that a one-to-one relationship enforces a unique constraint on the foreign key, while a many-to-one relationship does not.

What is a composite element in Hibernate and how is it used?

View answer

Hide answer

In Hibernate, a composite element represents a part of a collection element that contains multiple attributes. It is used to map a collection of value objects that contain multiple properties to a database table. A composite element is defined using the **@org.hibernate.annotations.CollectionOfElements**annotation in Hibernate, and the properties of the value object are mapped using @org.hibernate.annotations.Columns. For example, a collection of Address objects can be defined as a composite element within an **Employee**entity, where each Address object has multiple properties such as street, city, and zipCode.

What is the difference between a natural and a surrogate primary key in Hibernate?

View answer

Hide answer

A natural primary key is a primary key that is based on a unique business identifier for an entity, such as an email address or social security number. A surrogate primary key is a primary key that is system-generated and has no meaning outside of the database, such as an auto-incrementing integer. In Hibernate, it is recommended to use a surrogate primary key to ensure uniqueness and avoid changes to natural keys. Here's an example of defining a surrogate primary key in Hibernate using annotations:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // other entity fields and mappings
    // ...
}

How do you implement a custom type in Hibernate?

View answer

Hide answer

To implement a custom type in Hibernate, you need to implement the org.hibernate.UserType interface. This interface defines methods for converting values between Java and JDBC types, and for deep copying and comparing values. You can also define a custom nullSafeGet method to handle NULL values. Once you have implemented the UserType interface, you can register it with Hibernate using either annotations or XML mappings. Here is an example implementation of a custom EmailType that maps to a VARCHAR column in the database:

public class EmailType implements UserType {

    // implementation of UserType interface methods
    // ...

    public Class<?> returnedClass() {
        return Email.class;
    }

    public int[] sqlTypes() {
        return new int[] {Types.VARCHAR};
    }

    public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException {
        String value = rs.getString(names[0]);
        return value != null ? new Email(value) : null;
    }

    // ...
}

What is a custom dialect in Hibernate and how is it used?

View answer

Hide answer

A custom dialect in Hibernate is used to define how Hibernate should generate SQL statements for a specific database. It is a class that extends the Hibernate Dialect class and overrides methods to customize the SQL generation behavior. The custom dialect can be used to handle differences in SQL syntax, data types, or functions between different databases. It is typically defined in the Hibernate configuration file and can be specified at the session factory level or for specific sessions. Below is an example of a custom dialect for MySQL:

public class MySQLDialect extends Dialect {
    public MySQLDialect() {
        super();
        registerColumnType(Types.BIT, "tinyint(1)");
        registerColumnType(Types.TIMESTAMP, "datetime");
        // other overrides
    }
}

How do you use the Hibernate Validator to validate data?

View answer

Hide answer

Hibernate Validator is used to validate data using annotations. It provides a set of predefined annotations like @NotNull, @Size, @Email, etc. that can be used to validate data. To use Hibernate Validator, you need to add it as a dependency in your project and annotate the fields in your entity classes with the appropriate annotations. Here's an example of using @NotNull to validate a field:

public class User {

    @NotNull
    private String name;

    // other fields and methods
}

In this example, the name field will be validated to ensure that it is not null. If it is null, a validation error will be thrown.

What is a filter in Hibernate and how does it work?

View answer

Hide answer

A filter in Hibernate is a mechanism that allows you to define additional conditions that will be applied to an entity or collection when retrieved from the database. Filters are defined in the mapping file and can be enabled or disabled at runtime, which allows you to apply different filter conditions based on specific use cases. Filters are typically used to implement data-level security or to implement multi-tenancy by restricting access to certain data based on the current user or tenant. Here's an example of defining a filter in a mapping file:

<class name="com.example.Order" table="orders">
  <id name="id" column="order_id">
    <generator class="increment"/>
  </id>
  <property name="orderNumber" column="order_number"/>
  <property name="amount" column="amount"/>

  <filter name="orderLimit" condition="amount > :minAmount"/>
</class>

To enable the filter at runtime, you can use the enableFilter method of the Hibernate Session:

Session session = sessionFactory.getCurrentSession();
session.enableFilter("orderLimit").setParameter("minAmount", 100.0);
List orders = session.createQuery("from Order").list();

This will retrieve all orders with an amount greater than 100.0, as defined by the filter condition.

What is the difference between an entity and a value object in Hibernate?

View answer

Hide answer

In Hibernate, an entity is a persistent object with an identity that is uniquely identified by a primary key. It has a lifecycle and can be managed by the Hibernate Session. On the other hand, a value object is an object that holds values but has no identity. It is not uniquely identified by a primary key and is often used to represent complex data types. Value objects are usually embedded in entities or collections of entities. A value object is immutable and its state should not change once it is created.

How do you use the Hibernate Envers library for auditing purposes?

View answer

Hide answer

Hibernate Envers is a library used for auditing and versioning of entities. To use it, you need to annotate the entities you want to audit with @Audited annotation. Once annotated, Envers will automatically create an audit table for each audited entity with an additional set of columns to track revisions. You can then retrieve a specific revision of an entity using AuditReader or query revisions using AuditQuery. Here's an example:

@Entity
@Audited
public class Customer {
    @Id
    @GeneratedValue
    private Long id;

    private String name;

    // getters and setters
}

// Retrieving a specific revision
AuditReader reader = AuditReaderFactory.get(entityManager);
Customer customer = reader.find(Customer.class, customerId, revision);

// Querying revisions
AuditQuery query = reader.createQuery().forRevisionsOfEntity(Customer.class, true, true);
List<Customer> revisions = query.getResultList();

What is a NamedNativeQuery in Hibernate and how does it work?

View answer

Hide answer

A NamedNativeQuery in Hibernate allows you to define a named SQL query that can be used to fetch or update data from the database using native SQL. It differs from NamedQuery in that it executes native SQL rather than HQL. You can specify the SQL query and its parameters using annotations or in an XML configuration file. Here's an example of using NamedNativeQuery to fetch data from a database:

@NamedNativeQuery(
    name = "getEmployeeByName",
    query = "SELECT * FROM employee WHERE name = :name",
    resultClass = Employee.class
)
public class Employee {
    ...
}

This defines a named native query called getEmployeeByName that fetches all employees with a given name. The resultClass parameter specifies the class that the query results should be mapped to.

What is the difference between a uni-directional and a bi-directional association mapping in Hibernate?

View answer

Hide answer

In Hibernate, a uni-directional association mapping refers to a relationship between two entities where only one entity has a reference to the other entity, while the other entity does not have any knowledge about the relationship. In contrast, a bi-directional association mapping allows both entities to have a reference to each other, creating a two-way relationship. Bi-directional mappings can be more efficient when querying the database for related entities, but they require careful management of both sides of the relationship to avoid issues like infinite loops or inconsistent state.

How do you use the Hibernate Search library to implement full-text search?

View answer

Hide answer

Hibernate Search is a library that provides full-text search capabilities on top of Hibernate ORM. To use Hibernate Search, you need to annotate your entity classes with @Indexed and the fields you want to search with @Field. You can then use a FullTextEntityManager to perform searches. Here's an example:

@Entity
@Indexed
public class Book {
    @Id
    private Long id;

    @Field
    private String title;

    @Field
    private String description;

    // getters and setters
}

// performing a search
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory()
        .buildQueryBuilder()
        .forEntity(Book.class)
        .get();
Query luceneQuery = queryBuilder
        .keyword()
        .onFields("title", "description")
        .matching("Hibernate Search")
        .createQuery();
FullTextQuery jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, Book.class);
List<Book> results = jpaQuery.getResultList();

In this example, we have an entity class Book that is annotated with @Indexed and has two fields (title and description) annotated with @Field. We then create a FullTextEntityManager to get access to the Hibernate Search APIs, build a query using a QueryBuilder, and execute the search using a FullTextQuery. The search query looks for books that contain the words "Hibernate Search" in either the title or description fields. The results of the search are returned as a list of Book objects.

What is a metamodel in Hibernate and how is it used?

View answer

Hide answer

In Hibernate, a metamodel is a programmatic interface that provides type-safe access to the metadata of a persistence unit, such as entity classes, their attributes, and relationships. It is used to improve the type safety and readability of queries by allowing developers to reference persistent classes and properties by their names in the code rather than as strings, which helps to avoid errors and makes the code more maintainable. Here's an example of using the metamodel to obtain a reference to an entity's attribute:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Customer> query = builder.createQuery(Customer.class);
Root<Customer> customer = query.from(Customer.class);
query.where(builder.equal(customer.get(Customer_.lastName), "Smith"));

What is the difference between a batch and a single insert in Hibernate?

View answer

Hide answer

In Hibernate, a single insert operation is when an entity object is saved to the database individually. A batch insert operation is when multiple entity objects are saved to the database at once, using a single transaction. Batch inserts are typically faster than single inserts because they reduce the overhead of database connections and transaction management. Here is an example of batch insert using Hibernate's session:

s
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

for (int i = 0; i < entities.size(); i++) {
    session.save(entities.get(i));
    if (i % batchSize == 0) {
        session.flush();
        session.clear();
    }
}

transaction.commit();
session.close();

How do you use the Hibernate EntityManager API?

View answer

Hide answer

The Hibernate EntityManager API provides a high-level, object-oriented interface for performing CRUD operations on entities. To use the EntityManager API, you first obtain an EntityManager instance via an EntityManagerFactory, and then use its methods to persist, retrieve, update, and delete entities. For example:

// obtain an EntityManagerFactory
EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");

// obtain an EntityManager
EntityManager em = emf.createEntityManager();

// persist an entity
em.getTransaction().begin();
em.persist(myEntity);
em.getTransaction().commit();

// retrieve an entity
MyEntity retrievedEntity = em.find(MyEntity.class, entityId);

// update an entity
em.getTransaction().begin();
retrievedEntity.setProperty(newValue);
em.getTransaction().commit();

// delete an entity
em.getTransaction().begin();
em.remove(retrievedEntity);
em.getTransaction().commit();

// close the EntityManager
em.close();

// close the EntityManagerFactory
emf.close();

In addition to the basic CRUD operations, the EntityManager API also provides support for transactions, caching, query execution, and more.

What is a versioning strategy in Hibernate and how does it work?

View answer

Hide answer

A versioning strategy in Hibernate is used to manage the state of an object during concurrent access. It allows for optimistic locking, where an object can be modified by multiple threads or transactions concurrently, and Hibernate ensures that changes are not lost by using versioning. The version number is typically an integer or a timestamp that is incremented each time the object is modified. When a transaction tries to modify an object, Hibernate checks if the version number has changed since the object was last read, and if so, it throws an exception to prevent data loss. Versioning can be implemented using annotations or XML mapping files in Hibernate.

How do you use the Hibernate Interceptor API to intercept and modify SQL queries?

View answer

Hide answer

The Hibernate Interceptor API allows intercepting and modifying SQL queries executed by Hibernate. To use it, you need to implement the Interceptor interface and override its methods. For example, to modify a SQL query, you can override the onPrepareStatement method. Then, you can register your interceptor with the SessionFactory using the setInterceptor method or with the Session using the setInterceptor method. Here's an example:

public class CustomInterceptor extends EmptyInterceptor {
    @Override
    public String onPrepareStatement(String sql) {
        // Modify the SQL query
        String modifiedSql = sql.replace("SELECT", "SELECT DISTINCT");

        return super.onPrepareStatement(modifiedSql);
    }
}

// Register the interceptor with the SessionFactory
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
CustomInterceptor interceptor = new CustomInterceptor();
sessionFactory.setInterceptor(interceptor);

// Use the SessionFactory to create a Session
Session session = sessionFactory.openSession();

// Or register the interceptor with the Session
CustomInterceptor interceptor = new CustomInterceptor();
Session session = sessionFactory.openSession(interceptor);
Other Interview Questions

ReactJS

Business Analyst

Android

Javascript

Power BI Django .NET Core
Drupal TestNG C#
React Native SAS Kubernetes
Check Other Interview Questions
customers across world
Join 1200+ companies in 75+ countries.
Try the most candidate friendly skills assessment tool today.
GET STARTED FOR FREE
g2 badges
logo
40 min tests.
No trick questions.
Accurate shortlisting.

[email protected]

Product
  • Product Tour
  • Science
  • Pricing
  • Features
  • Integrations
  • AI Resume Parser
Usecases
  • Aptitude Tests
  • Coding Tests
  • Psychometric Tests
  • Personality Tests
Helpful Content
  • Skills assessment tools
  • 52 pre-employment tools compared
  • Compare Adaface
  • Compare Codility vs Adaface
  • Compare HackerRank vs Adaface
  • Compare Mettl vs Adaface
  • Online Compiler
BOOKS & TOOLS
  • Guide to pre-employment tests
  • Check out all tools
Company
  • About Us
  • Join Us
  • Blog
Locations
  • Singapore (HQ)

    32 Carpenter Street, Singapore 059911

    Contact: +65 9447 0488

  • India

    WeWork Prestige Atlanta, 80 Feet Main Road, Koramangala 1A Block, Bengaluru, Karnataka, 560034

    Contact: +91 6305713227

© 2023 Adaface Pte. Ltd.
Terms Privacy Trust Guide

🌎 Pick your language

English Norsk Dansk Deutsche Nederlands Svenska Français Español Chinese (简体中文) Italiano Japanese (日本語) Polskie Português Russian (русский)
Search 500+ tests by skill or role name
JavaScript
React
How many questions will be there in AWS test?
What test do you recommend for analysts?