Hibernate Interview Questions and answers Part -2


Question Answer Example Code
What is the purpose of the @Entity annotation in Hibernate? Marks a class as a Hibernate entity, mapping it to a database table. java @Entity public class Employee { @Id @GeneratedValue private int id; private String name; }
What is the purpose of the @Table annotation in Hibernate? Specifies the table name and schema. java @Entity @Table(name = "employees") public class Employee { @Id @GeneratedValue private int id; }
What is the difference between @Id and @GeneratedValue? @Id marks a field as the primary key, while @GeneratedValue defines how the key is generated. java @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id;
What is the purpose of @Column annotation? Defines column properties such as name, length, and uniqueness. java @Column(name = "emp_name", length = 50, unique = true) private String name;
What is the difference between @OneToOne and @OneToMany relationships? @OneToOne: One entity related to one entity. @OneToMany: One entity related to multiple entities. java @OneToOne private Address address; @OneToMany(mappedBy = "department") private List<Employee> employees;
What is the difference between @ManyToOne and @ManyToMany relationships? @ManyToOne: Multiple entities linked to a single entity. @ManyToMany: Many-to-many relationship between entities. java @ManyToOne private Department department; @ManyToMany private List<Course> courses;
What is the use of @JoinColumn in Hibernate? Defines the foreign key column in a relationship. java @OneToOne @JoinColumn(name = "address_id") private Address address;
What is optimistic and pessimistic locking in Hibernate? Optimistic Locking: Uses versioning (@Version) to prevent conflicts. Pessimistic Locking: Locks a record to prevent concurrent modifications. java @Version private int version;
What is the use of @Embedded and @Embeddable annotations? Enables embedding one class into another without creating a separate table. java @Embeddable public class Address { private String city; private String state; } @Entity public class Employee { @Embedded private Address address; }
What is a Named Query in Hibernate? A predefined query that can be reused. java @NamedQuery(name = "Employee.findAll", query = "FROM Employee") public class Employee { } Query query = session.getNamedQuery("Employee.findAll"); List<Employee> employees = query.list();
What is a Native SQL query in Hibernate? Executes raw SQL queries. java Query query = session.createSQLQuery("SELECT * FROM employees").addEntity(Employee.class); List<Employee> employees = query.list();
What are the different fetching strategies in Hibernate? Lazy Fetching: Loads data when needed. Eager Fetching: Loads related data immediately. java @OneToMany(fetch = FetchType.LAZY) @OneToMany(fetch = FetchType.EAGER)
What is Hibernate Interceptor? Allows custom logic before or after database operations. java class MyInterceptor extends EmptyInterceptor { @Override public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { System.out.println("Entity deleted: " + entity); } } Session session = sessionFactory.withOptions().interceptor(new MyInterceptor()).openSession();
What is the difference between clear(), evict(), and close() in Hibernate? clear(): Removes all objects from session cache. evict(Object obj): Removes a specific object from cache. close(): Closes session completely. java session.evict(employee); session.clear(); session.close();
What is the difference between Hibernate and JPA? JPA is a specification for ORM, while Hibernate is an implementation of JPA with extra features. java @Entity public class Employee { }


Hibernate Interview Questions and answers part -1

Here is the formatted table with Hibernate interview questions and answers:

SNO   Question Answer
1 What is Hibernate? Hibernate is an open-source ORM framework in Java. It simplifies database interaction by mapping Java objects to database tables and automating CRUD operations.
2 What are the main advantages of Hibernate over JDBC? - No cumbersome JDBC boilerplate code - Supports automatic SQL query generation - Faster processing due to caching - Supports HQL (Hibernate Query Language) - Built-in transaction management
3 What is HQL (Hibernate Query Language)? HQL is an object-oriented query language in Hibernate that uses entity names instead of table names. Example: java <br> Query query = session.createQuery("FROM Employee WHERE department = 'IT'"); <br> List<Employee> employees = query.list(); <br>
4 What are the different states of a Hibernate object? - Transient – The object is not associated with any Hibernate session. - Persistent – The object is in a session and mapped to a database row. - Detached – The object was persistent but is now outside the session.
5 What is the difference between get() and load() in Hibernate? - get() – Fetches data immediately; returns null if no record is found. - load() – Uses lazy loading; throws an exception if no record is found.
6 What is caching in Hibernate? Caching improves performance by reducing database queries. - First-level cache – Enabled by default; stores data within a session. - Second-level cache – Shared across multiple sessions; requires explicit configuration.
7 What is the difference between save() and persist() in Hibernate? - save() – Returns the generated identifier and inserts the record immediately. - persist() – Does not return an ID; insertion occurs only when the transaction commits.
8 What is the difference between Session and SessionFactory? - SessionFactory – A heavyweight object that creates Session instances; spans the entire application. - Session – A lightweight object representing a unit of work; interacts with the database.
9 What are Hibernate Annotations? Hibernate annotations allow entity mappings without XML. Example: java <br> @Entity <br> @Table(name = "employees") <br> public class Employee { <br> @Id <br> @GeneratedValue <br> private int id; <br> private String name; <br> } <br>
10 How does Hibernate handle transactions? Hibernate transactions are managed using Transaction objects. Example: java <br> Transaction tx = session.beginTransaction(); <br> session.save(employee); <br> tx.commit(); <br>
11 What is the difference between merge() and update() in Hibernate? - update() – Reattaches a detached object to the session and updates it. - merge() – Merges changes from a detached object into a persistent object copy.
12 What is Lazy and Eager loading in Hibernate? - Lazy Loading – Data is not retrieved until needed. - Eager Loading – Related entities are retrieved immediately. Example: java <br> @OneToMany(fetch = FetchType.LAZY) // Lazy loading <br> @OneToMany(fetch = FetchType.EAGER) // Eager loading <br>
13 What are the different inheritance strategies in Hibernate? Hibernate supports three inheritance mapping strategies: - Single Table Strategy – @Inheritance(strategy = InheritanceType.SINGLE_TABLE) - Joined Table Strategy – @Inheritance(strategy = InheritanceType.JOINED) - Table Per Class Strategy – @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
14 What is the Criteria API in Hibernate? The Criteria API allows dynamic queries without writing HQL. Example: java <br> Criteria criteria = session.createCriteria(Employee.class); <br> criteria.add(Restrictions.eq("department", "IT")); <br> List<Employee> employees = criteria.list(); <br>
15 What is the difference between openSession() and getCurrentSession()? - openSession() – Always creates a new session. - getCurrentSession() – Returns an existing session if available.

Hibernate Native sql query with example

  • By Using Hibernate Native SQL we can write database dependent queries as part of hibernate.
  • Hibernate Native Sql allows us to write create , update,  delete and insert queries.
  • We can also call Stored procedures using Hibernate Native Sql.
  • When the query is too complex using HQL then we need to use hibernate sql query.
  • Hibernate uses the org.hibernate.SQLQuery interface for native SQL
    1. SQLQuery is a sub interface of Query
    2. Use createSQLQuery() factory method on Session to create SQLQuery object.
  •  Hibernate SQLQuery must be associated with an existing Hibernate entity or scalar result.



Hibernate native sql insert query example

  1. Session session = sessionFactory.openSession();
  2. session.beginTransaction();
  3.  
  4. SQLQuery insertsqlQuery = session.createSQLQuery("INSERT INTO
  5. Physician(firstname,lastname,fee,hospital)VALUES(?,?,?,?)");
  6.  
  7.  insertsqlQuery.setParameter(0, "Saidesh");
  8.  insertsqlQuery.setParameter(1, "Kilaru");
  9.  insertsqlQuery.setParameter(2, 50); 
  10.  insertsqlQuery.setParameter(3, "Yashoda");        
  11.  insertsqlQuery.executeUpdate();

 Hibernate scalar query example

  • Writing a Hibernate Sql query to get list of  scalars or values from single or multiple tables.
  • Lets see an example on Hibernate scalar query.


  1. String hibernate_sql = "SELECT first_name, fee FROM  Physician";
  2. SQLQuery query = session.createSQLQuery(hibernate_sql);
  3. query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
  4. List results = query.list();

 Hibernate named sql Queries

  • Writing a Hibernate Sql query to get entity object by using addEntity() method.
  • Lets see an example on Hibernate named sql query

hibernate native sql query parameters scalar


Hibernate Named Query Introduction Tutorial

  • If we are using HQL or Native SQL queries multiple time then it will be code mess because all queries will be scattered throughout the project.
  • Hibernate Named Query is a way to use queries by giving a name.
  • Hibernate Named Queries will be defined at one place and used anywhere in the project.
  • use of named query in hibernate
  • Writing HQL query in HBM file is called HQL Named Query.
  • Or we can use @NameQuery annotation in entity.
  • For writing Hibernate Named Queries we will use <query> tag in Hibernate mapping file Or @NameQuery annotation in the entity.
  • If we want to create Named Query using hibernate mapping file then we need to use query element.



Advantages of Named Query in Hibernate 

  • Global access
  • Easy to maintain.

Hibernate Named Queries by using Annotations:

  • If we want to create Named Queries using annotations in entity class then we need to use @NameQueries and @NameQuery annotations
  • @NameQuery will be used to create single Query
  • @NameQueries annotations will be used to create multiple Queries. When we are using @NameQueries for every query we need to use @NameQuery annotation.

Hibernate Named Query example by using Annotations:


Hibernate Named Query example join

  1. Query query = session.getNamedQuery("findDocterById");
  2.         query.setInteger("id", 37);
  3.        List empList = query.list();


Hibernate Named Queries by using Hibernate mapping file:

  • We need to configure Hibernate Named Queries as part of Hibernate mapping file.
  • By using <query> element we need to write Hibernate named Queries.

  1. <hibernate_mapping>
  2.             <class  >
  3.             ---------
  4.             </class>
  5.  
  6.  <query name = “findDocterById”>
  7.  <![CDATA[from Docter s where s.id = :id]]>
  8. </query>  

  9.  </hibernate_mapping>     


  1. Query query = session.getNamedQuery("findDocterById");
  2.         query.setInteger("id", 64);
  3.        List empList = query.list();

Hibernate Criteria Query Language (HCQL)

  • In Hibernate we pull the data from data base in two ways.
  • session.get()/ session.load()
  • Hibernate query langugae
  • Now we will discuss about the third way Hibernate criteria query language which solves the problems of above two approaches.




Hibernate Criteria Query Language / HCQL

  • In order to fetch the records based on some criteria we use Hibernate Criteria Query Language.
  • We can make select operation on tables by applying some conditions by using HCQL.
  • Criteria API is the alternative to HQL in object oriented approach.  
  • We can execute only SELECT statements using Criteria; we can’t execute UPDATE, DELETE statements using Criteria.

Advantages of  Hibernate Criteria Query Language (HCQL) 

  • Criteria API allows us to define criteria query object by applying rules ,filtration and logical conditions
  • So that we can add criteria to query.
  • Criteria is also database independent, Because it internally generates HQL queries.
  • Criteria is suitable for executing dynamic queries
  • Criteria API also include Query by Example (QBE) functionality for supplying example objects.
  • Criteria also includes projection and aggregation methods
     

Criteria Interface:

  • Criteria Interface has some methods to specify criteria.
  • Hibernate session interface has a method named createCriteria() to create criteria.

  1. public interface Criteria  extends CriteriaSpecification

  1. Criteria criteria = session.createCriteria(Student.class);
  2. List<Student> studentList= criteria .list();

Methods of Criteria interface:

  
Hibernate add crieria example hcql


Order Class

  1. public class Order extends Object implements Serializable
 
  • By using Order class we can sort the records in ascending or descending order.
  • Order class provides two different methods to make ascending and descending.
  1. public static Order asc(String propertyName)
  2. public static Order desc(String propertyName)

Hibernate Criteria query example using order class

  1.  Criteria criteria = session.createCriteria(Product.class)
  2.  
  3. // To sort records in descening order
  4. criteria.addOrder(Order.desc("price"));
  5.  
  6. // To sort records in ascending order
  7. criteria.addOrder(Order.asc("price"));

Restrictions Class

  1. public class Restrictions extends Object

  • Restrictions class provides methods that can be used  add restrictions (conditions) to criteria object.
  • We have many methods in Restrictions class some of the commonly using methods are.

hibernate criteria add example interview questions


Hibernate Criteria query example using Restrictions class


  1.  Criteria criteria = session.criteriaeateCriteria(Product.class);
  2. // To get records having price more than 3000
  3. criteria.add(Restrictions.gt("price", 3000));
  4.  
  5. // To get records having price less than 2000
  6. criteria.add(Restrictions.lt("price", 2000));
  7.  
  8. // To get records having productName starting with criteriaite
  9. criteria.add(Restrictions.like("productName", "criteriaite%"));
  10.  
  11. // Case sensitive form of the above restriction.
  12. criteria.add(Restrictions.ilike("productName", "zara%"));
  13.  
  14. // To get records having price in between 1000 and 2000
  15. criteria.add(Restrictions.between("price", 1000, 2000));
  16.  
  17. // To check if the given property price is null
  18. criteria.add(Restrictions.isNull("price"));
  19.  
  20. // To check if the given property is not null
  21. criteria.add(Restrictions.isNotNull("price"));
  22.  
  23. // To check if the given property price is empty
  24. criteria.add(Restrictions.isEmpty("price"));
  25.  
  26. // To check if the given property price is not empty
  27. criteria.add(Restrictions.isNotEmpty("price"));
  28.  
  29. List results = criteria.list();

Pagination using Hibernate Criteria

  • By using criteria methods setFirstResult() and setMaxResults() we can achieve pagination concept.


  1. Criteria criteria = session.createCriteria(Product.class);
  2. criteria.setMaxResults(10);
  3. criteria.setFirstResult(20);

Projections class in Hibernate

  1. public final class Projections extends Object

  • By Using org.hibernate.criterion.Projections  class methods we can perform operations like minimum , maximum, average , sum and count.

Hibernate Criteria query example using Projection class

  1. Criteria criteria = session.criteriaeateCriteria(Product.class);
  2.  
  3. // To get total row count.
  4. criteria.setProjection(Projections.rowCount());
  5.  
  6. // To get average price.
  7. criteria.setProjection(Projections.avg("price"));
  8.  
  9. // To get distinct countof name
  10. criteria.setProjection(Projections.countDistinct("name"));
  11.  
  12. // To get maximum price
  13. criteria.setProjection(Projections.max("price"));
  14.  
  15. // To get minimum price
  16. criteria.setProjection(Projections.min("price"));
  17.  
  18. // To get sum of price
  19. criteria.setProjection(Projections.sum("price"))

Hibernate Query Langugae (HQL)

Hibernate Query Language:

  • HQL is one of the feature of Hibernate.
  • HQL is same like SQL but here it uses class name as table name and variables as columns.
  • HQL is Database independent query language.
  • An object oriented form of SQL is called HQL
  • HQL syntax is very much similar to SQL syntax.  Hibernate Query Language queries are formed by using Entities and their properties, where as SQL quires are formed by using Tables and their columns.
  • HQL Queries are fully object oriented..
  • HQL Queries are case sensitive.


Advantages of HQL:

  • Database Independent
  • HQL Queries supports inheritance and polymorphism
  • Easy to learn. 

Query Interface:

  • Query interface used to Represent HQL query in the form of query object.
  • The object of  query will be created by calling createQuery(hql query) method of session.

  1.  Session hsession = sf.openSession();
  2. Query query = hsession.createQuery(hql query);

  • Send the query object to hibernate software by calling the list method.
  • Hibernate returns an ArrayList object render the ArrayList object and display the output to client.

  1. List l = query.list();
  2. ArrayList emplist = (ArrayList)l;

  • Query is an interface which is available as port of org.hibernate package. We can not create the object to query interface. We can create a reference variable and it holds implementation class object.

 Methods of Query Interface:

HQL hibernate query language

Advantages and disadvantages of hibernate compared to jdbc

Advantages of Hibernate over JDBC:

  1. Hibernate is an ORM tool
  2. Hibernate is an open source framework.
  3. Better than JBDC.
  4. Hibernate has an exception translator , which converts checked exceptions of JDBC in to unchecked exceptions of hibernate. So all exceptions in hibernate are unchecked exceptions and Because of this no need to handle exceptions explicitly.
  5. Hibernate supports inheritance and polymorphism.
  6. With hibernate we can manage the data stored across multiple tables, by applying relations(association)
  7. Hibernate has its own query language called Hibernate Query Language. With this HQL hibernate became database independent.
  8. Hibernate supports relationships like One-To-One, One-To-Many, Many-To-One ,Many-To-Many.
  9. Hibernate has Caching mechanism. using this number of database hits will be reduced. so performance of an application will be increases.
  10. Hibernate supports lot of databases.
  11. Hibernate supported databases List.
  12. Hibernate is a light weight framework because hibernate uses POJO classes for data transfer between application and database.
  13. Hibernate has versioning and time stamp feature with this we can know how many number of times data is modified.
  14. Hibernate also supports annotations along with XML.
  15. Hibernate supports Lazy loading.
  16. Hibernate is easy to learn it is developers friendly.
  17. The architecture is layered to keep you isolated from having to know the underlying APIs.
  18. Hibernate maintains database connection pool.
  19. Hibernate  has Concurrency support.
  20. Using Hibernate its Easy to maintain and it will increases productivity


Disadvantages of Hibernate Compared to JDBC!!:
  • Hibernate is slow compared to JDBC because of generating many sql queries at run time but this is not considered as dis advantage in my view.
  • Below are some of the dis advantages but these are not applicable to small applications. But we have given some possible scenarios. 

advantages and disadvantages of hibernate

Select Menu