Top 100 Hibernate Interview Questions And Answers

Hibernate Interview questions are asked for experienced applicants. These hibernate interview questions will brush up your knowledge before the interview. Top 100 hibernate interview questions are designed for both freshers and professionals. Following important Hibernate interview questions could be categorized into basic, intermediate, and advanced questions. 

Contents show

1. What is Hibernate? 

Starting with the basic level hibernate interview questions 

Hibernate is one of the most popular Java frameworks that simplify the development of Java applications to interact with databases. It is an Object Relational Mapping(ORM) tool. Hibernate also provides a reference implementation of Java API. 

hibernate interview questions and answers

2. What are major advantages of Hibernate Framework? 

It is one of the important Hibernate interview questions.

  • Open sourced and lightweight
  • Performance is fast
  • Helps to generate independent queries
  • Provides facilities to create a table
  • Query statistics ad database status 

3. What are the advantages of using Hibernate over JDBC? 

This is one of the most asked interview questions. 

  • Eliminates a lot of boilerplate code.
  • Supports inheritance, associations, and collections
  • HQL is more object-oriented and closer to Java
  • Implicitly provides transaction management
  • It wraps exceptions and throws JDBC exceptions which are the unchecked exceptions 

4. What is an ORM tool? 

This is one of the tricky interview questions 

A technique that maps the object that is stored in the database. An ORM tool helps in simplifying data creation, manipulation, and access. 

Java Application-> Object-> ORM-> Database

5. Why use Hibernate Framework? 

This is among entry-level interview questions.  

  • Overcomes the database dependency faced in the JDBC
  • Changing of the databases cost a lot working on JDBC
  • Code portability is easily handled  

6. What are different functionalities supported by Hibernate? 

  • It is an ORM tool
  • It uses HQL
  • It supports auto DDL operations 
  • It also has an Auto Primary Key Generation support 
  • Supports cache memory 
  • Exception handling is not mandatory 

7. What are technologies that are supported by Hibernate? 

  • XDoclet Spring
  • J2EE
  • Eclipse plug-ins
  • Maven

8. What is HQL? 

HQL is the acronym of Hibernate Query Language. It is an Object-Oriented Query Language and is independent of the database.   

9. How to achieve mapping in Hibernate? 

Association mappings are one of the key features of Hibernate. It supports the same associations as the relational database model. 

achieve mapping in Hibernate

10. Name some of the important interfaces of Hibernate framework?  

  • Session factory(org.hibernate.SessionFactory): Instance of this is used to retrieve Session objects for database operations.  
  • Session(org.hibernate.Session): Its factory for transaction, it’s used for connecting applications with persistent stores like hibernate framework/DB. 
  • Transaction(org.hibernate.Transaction): This specifies single / atomic units of work. 
important interfaces of Hibernate framework

11. What is One-to-One association in Hibernate? 

Model the system for the entity for which you want to navigate the relationship in your query or domain model. 

One-to-One association in Hibernate

12. What is the One-to-Many association in Hibernate?  

One object can be associated with multiple/different objects. Talking about the mapping, the One-to-Many mapping is implemented using a Set Java collection. 

the One-to-Many association in Hibernate

13. What is the many to many association in Hibernate? 

Many-to-many mapping requires an entity attribute and a @ManyToMany annotation. It can either be unidirectional and bidirectional. 

the many to many association in Hibernate

14. What do you mean by Hibernate Configuration File? 

Hibernate configuration files are dialect information, so that hibernate knows the database type and mapping file or class details. 

It contains database-specific configurations.  

15. Mention some important annotations used for mapping. 

  • javax.persistence.Entity
  • javax.persistence.Table
  • javax.persistence.Access
  • javax.persistence.Embeddedid
  • javax.persistence.Column
  • javax.persistence.GeneratedValue

16. How to integrate Hibernate and Spring? 

integrate Hibernate and Spring

There’s no need to use Hibernate Transaction Management

17. What is a session in Hibernate and how to get it? 

  • Create
  • Read
  • Update 
  • Delete

To get the session, you can execute HQL queries, SQL native queries using the session object.

18. What is the Hibernate Session factory? 

SessionFactory is the factory class that is used to get the Session objects. 

It is created during application startup and kept for later use. 

This SessionFactory is a thread-safe object which is used by all the threads of an application. 

19. What is the difference between openSession and getCurrentSession? 

getCurrentSession()openSession()
Returns the session bound to the context and for this to work, you need to configure it in the Hibernate configuration file. Helps in opening a new session. You should close this session object once you are done with all database operations.

20. How do you configure a Hibernate file?  

  • Identify the POJOs
  • Identify which properties of POJOs need to be continued
  • Annotate each of the POJOs
  • Create a database schema 
  • Add hibernate Java libraries
  • Create a hibernate XML configuration file
  • Create a Hibernate configuration object that refers to your XML configuration file
  • Build a hibernate SessionFactory object and retrieve  

21. What are the key components of a Hibernate configuration object? 

  • Database Connection 
  • Class mapping setup 

22. Discuss the collections in Hibernate. 

  • ArrayList
  • Vector

 A collection can be a list, sets, map, sorted set, sorted map, Java   

23. What are the types of collection in Hibernate? 

There are mainly five collection types used for one to many relationship mapping: 

  • Map
  • Sets
  • Array
  • List 
  • Bag

24. What are the benefits of using Hibernate templates

  • Automated Session closing ability 
  • The interaction with the Hibernate Session is simplified
  • Exception handling is automated   

25. Which are the design patterns that are used in the Hibernate framework? 

  • Domain Model pattern 
  • Data Mapper 
  • Proxy Pattern
  • Factory Pattern
  • Data access object (DAO)
  • Abstract factory
  • Object-Relational Mapping(ORM)
  • Query object 

Top Hibernate Interview Questions And Answers

26. Define Hibernate Validator Framework. 

Data validation is used in the presentation layer with the use of Javascript and the server-side code before processing.

Hibernate Validator Framework

27. How would you define automatic dirty checking?

Automatic dirty checking can be defined as a feature that helps us in saving the effort of explicitly asking Hibernate to update the database every time we modify or make changes to the state of an object inside a transaction. 

28. How can you share your views on mapping description files? 

  • Mapping description files are used by the Hibernate to configure functions. 
  • *.hbm extension, which facilitates the mapping between database tables and Java class. 
  • To use mapping description files or not this entirely depends on business entities.  

29. What is meant by Light Object Mapping? 

The syntax is hidden from the business logic using specific design patterns 

Light Object Mapping

30. What is meant by Hibernate tuning? 

This is among advanced hibernate interview questions. 

Hibernate tuning is a process of optimizing the performance of Hibernate applications. 

  • SQL Optimization 
  • Session Management
  • Data Caching 

31. What is transaction management in hibernate and how does it work? 

Transaction management is a process of managing a set of commands or statements. 

A transaction is associated with a session and is instantiated by calling session.beginTransaction().

32. How do you integrate Hibernate with Struts2 or Servlet web applications?

  • Register a custom ServletContextListener 
  • Initialize the Hibernate Session, store it in the servlet context.
  • Action class helps in getting the  Hibernate Session 

33. What are the different states of a persistent entity?  

  • Transient is not associated with the Session and has no representation in the database. 
  • Using Persistent you can make a transient instance persistent by associating it with a Session. 
  • Using Detached if you close the Hibernate Session, the persistent instances will become a detached instance. 

34. How can the primary key be created by using Hibernate?  

A primary key is a special relational database table column designated to uniquely identify all table records. It is specified in the configuration file hbm.xml.

<id name=”ClassID” type=”string” >
<column name= “columnID” length=”10” >
<generator/>
</id>

35. Explain about Hibernate Proxy and how it helps in Lazy loading? 

  • Hibernate uses a proxy object in order to support Lazy loading. 
  • Hibernate doesn’t load all the mapped objects.
  • After you reference a child object through getter methods, then the proxy code will be entered to the database. 
  • Uses Java assist to effectively and dynamically generate sub-classed implementations. 

36. How can we see Hibernate generated SQL on console? 

<property name=”show_sql” > true</property>

37. What is the query cache in Hibernate? 

Hibernate implements a separate cache region for queries result set that integrates with the Hibernate second-level cache. 

This is only useful for queries that are run frequently with the same parameters. 

<property name=”hibernate.cache.use_query_cache”>True</property>
Query query = session.createQuery(“from Employee”);
query.setCacheable(true);
query.setCacheRegion(“ALL_EMP”);

38. What is the benefit of Native SQL query support in Hibernate? 

Hibernate provides an option to execute Native SQL queries through the use of the SQL Query object. 

Native SQL Query comes in handy when you want to execute database-specific queries that are not supported by Hibernate API such as query hints or the Connect keyword in Oracle Database. 

39. What is Named SQL Query? 

You can define a Named SQL Query at a central location and use them anywhere in the code.

  • @NamedQuery
  • @NamedNativeQuery

40. When do you use merge() and update() in Hibernate?

Update: 

If you are sure that the Hibernate Session does not contain an already persistent instance with the same id. 

Merge():

Helps in merging your modifications at any time without considering the state of the Session. 

41. Difference between get() vs load() method in Hibernate?

load()get()
It will throw an exception, if an object with an ID passed to them is not found. Will return null 
Can return a proxy without hitting the database unless required. It always goes to the database. 

42. Difference between the first and second level cache in Hibernate. 

This one is among tricky hibernate interview questions. 

The first-level cache is maintained at Session level and is enabled by default.The second level cache is maintained at a SessionFactory level and is shared by all sessions. 

43. Difference between Session and SessionFactory in Hibernate. 

A session is a single-threaded, short-lived object. It provides the first-level cache. SessionFactory is immutable and shared by all Session. It also lives until the Hibernate is running. 

44. Difference between hibernate save(), saveOrUpdate() and persist() methods?

Hibernate save can be used to save entities to the database. The problem with save() is that it can be invoked without a transaction and if we have mapping entities, then only the primary object gets saved causing data inconsistencies.

 Also, save returns the generated id immediately. 

Hibernate persist is similar to saving with a transaction. I feel it’s better than save because we can’t use it outside the boundary of a transaction, so all the object mappings are preserved. 

Also persist doesn’t return the generated id immediately, so data persistence happens when needed.

Hibernate saveOrUpdate results into insert or update queries based on the provided data. If the data is present in the database, an update query is executed. 

We can use saveOrUpdate() without transaction also, but again you will face the issues with the mapped objects not getting saved if the session is not flushed. 

45. Difference between sorted and ordered collection in Hibernate. 

Sorted CollectionOrdered Collection
Sorted collections sort the data in JVM’s heap memory using Java’s collection framework sorting methods.The ordered collection is sorted using an order by clause in the database itself. 

46. Difference between the transient, persistent and detached state in Hibernate. 

Transient statePersistent state Detached state 
New objects are created in the Java program but are not associated with any Hibernate session.An object which is associated with a Hibernate session is called a Persistent object. You can call save() or persist()You can reattach a detached object to Hibernate sessions by calling either update() or saveOrUpdate() method 

47. Difference between managed associations and Hibernate associations?

Managed associationsHibernate associations
Relate to container management persistence and are bi-directional These associations are unidirectional 

48. What are the best practices that Hibernate recommends for persistent classes? 

  • Java classes need a default constructor 
  • Classes should contain an ID
  • Attributes should be declared private

49. What are the best practices to follow with the Hibernate framework? 

  • For web applications, always try to use JNDI DataSource rather than configuring to create a connection in hibernate.
  • Prefer DAO pattern for exposing the different methods that can be used with entity bean.
  • For collections, try to use Lists, maps and sets. Avoid arrays because you don’t get the benefit of lazy loading. 
  • Avoid Many-to-Many relationships, it can be easily implemented using bidirectional One to Many and Many-to-One relationships.
  • Always check the primary key field access. 
  • By default hibernate sets the field values directly, without using setters.
  • Use native sql query only when it can’t be done using HQL.
  • Use named queries wisely, keep it at a single place for easy debugging. 

50. How is the mapping done between object and database tables? 

Hibernate provides two methods so that you can connect with your database tables.

It provides JPA implementation hence we can use JPA annotations as well as XML configurations to achieve this mapping. 

Top Hibernate Interview Questions And Answers

51. What are Hibernate mapping files? 

The mapping file name conventionally should be class_name.hbm.xml.

  • Hibernate-mapping: root element 
  • Class: specifies the persistent class
  • Id: specifies the primary key attribute in the class
  • Generator: used to generate the primary key
  • Property: specifies the property name of the Persistent class
<?xml version=’1.0’ encoding= ’UTF-8’ ?>
<!DOCTYPE hibernate-mapping PUBLIC
   “-//Hibernate/Hibernate Mapping DTD 5.3 //EN”
   “http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd”>
<hibernate-mapping>
   <class name=”com.codedecode.Employee” table=”empTable”>
      <id name=”id”>
         <generator class=”assigned”></generator>
        </id>
        <property name=”firstName”></property> 
        <property name=”lastName”></property>
   </class>
   </hibernate-mapping>

52. What are the steps to create a sample application of Hibernate? 

  • Create a Java object 
  • Create mapping file 
  • Create database connection 
  •  Implementing class used for used for storing or getting data using POJO  
steps to create a sample application of Hibernate

53. What are the types of Hibernate caching?

types of Hibernate caching

54. Configure Hibernate Second Level Cache using EHCache.

Second level cache is maintained at SessionFactory level.

  • Add hibernate-ehcache dependency in your maven project, if it’s not maven then add corresponding jars. 
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
</dependency>
  • Add below properties in the hibernate configuration file.
< 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=”net.sf.ehcache.configurationResourceName”>/coded|ecodeehcache.xml</property>
* Create EHCache configuration file, a sample file codedecodeehcache.xml is as below:
<?xml version=“1.0 encoding=“UTF-8”?>
<ehcache xmlmd:xsi=“https://www.w3.org/2001/XMLSchema-instance”
       xsi:noNamespaceSchemaLocation=“ehcache.xsd” updateCheck=“true”
       monitoring=“autodetect” dynamicConfig=“true”>
      <diskStore path=“java.io.tmpdir/ehcache”/>
       <defaultCache maxEntriesLocalHeap=“10000” eternal=“false”
              timeToIdleSeconds=“120” timeToLiveSeconds=“120” diskSpoolBufferSizeMB=“30”
               maxEntriesLocalDisk=“10000000” diskExpiryThreadIntervalSeconds=“120”
               memoryStoreEvictionPolicy=“LRU” statistics=“true”>
                <persistence strategy=“localTempSwap” />
          </defaultCache>
           <cache name=“employee” maxEntriesLocalHeap=“10000” eternal=“false”
                     timeToIdleSeconds=“5” timeToLiveSeconds=“10”
                      <persistence strategy=“localTempSwap” />
             </cache>
           <cache name=“org.hibernate.cache.spi.UpdateTimestampsCache”
maxEntriesLocalHeap=“5000” eternal=“true”>
                 <persistence strategy=“localTempSwap” />
             </cache>
          </ehcache>
  • Annotate entity beans with @Cache annotation and caching strategy to use 
Import org.hibernate.annotations.Cache;
Import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity   
@Table( name = “ADDRESS”)
@Cache (usage=CacheConcurrencyStrategy.READ_ONLY, region=”employee”)
Public class Address {
}

55. I want specific database independent code in my project. How can I do that?

Use any ORM framework like Hibernate, Ibatis. 

56. How should I fetch a list of objects through the get or load method? 

  • It is not possible to fetch a list of data/objects.
  • get or  load method takes a single identifier only. 

57. Can you log generated sql queries by hibernate? How? 

You can log generated SQL queries by hibernate using the following commands

  1. show_sql=true
  2. logging.level.org.hibernate.SQL=DEBUG

58. Is it good to turn on sql logging for production env? 

  • No generally we do not prefer. 
  • Better to set log level of hibernate as error, logging.level.org.hibernate = ERROR

59. How to validate the schema? 

This is an advanced-level interview question. 

Use hbm2ddl=validate in order to validate the schema. 

60. I want to fetch all values in a particular column from a table. How do you do? 

  • Use projection from Hibernate
  • Use JPA CriteriaBuilder
  • Use JPQL

61. What are the different data types supported in Hibernate? 

Hibernate data type plays an important role as it acts as a bridge between java types and DB data types. 

  • Primitive types 
  • Data and time types
  • Binary and large object types 
  • Other JDK-related types

62. Which element is used in the hibernate maps java.util.SortedMap property? 

  • <map>

63. What is the return type of save ()?

  • java.io.Serializable.

64. What is the criteria object in Hibernate? 

It is used to create and execute object-oriented queries to retrieve the object.  

65. What is the Java Persistence API(JPA)?

JPA stands for Java Persistence API. It provides specifications for managing the relational data in applications. 

66. What do you know about transaction file? 

Transactions denote a work file that can save changes made or revert back the changes. A transaction can be started by session.beginTransaction() and it uses JDBC connection, CORBA, or JTA. 

When this session starts several transactions may occur. 

67. What is the difference between add jar() and add directory() methods? 

These methods are the most convenient to use in hibernate. These methods allow you to load all your hibernate documents at a time. 

These methods simplify code configuration, refactoring layout, etc. These functions help you to add your hibernate mapping to Hibernate initialization files. 

68. What are POJOs?

POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. Besides, they can also have some business logic related to that property. 

69. What does hibernate code look like? 

Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
MyPersistanceClass mpc = new MyPersistanceClass (“Sample App”);
session.save(mpc);
tx.commit();
Session close();

70. What are the different methods of identifying an object? 

  • Object identity
  • Object equality
  • Database identity 

71. What are the ORM levels in hibernate? 

There are four ORM levels in hibernate.

  • Pure Relational
  • Light Object Mapping 
  • Medium Object Mapping
  • Full Object Mapping 

72. What are the databases that hibernate supports? 

Some database engines supported by Hibernate: 

  • Oracle
  • MySQL
  • PostgreSQL
  • SAP DB
  • Sybase ASE
  • H2 Database
  • Microsoft SQL Server Database
  • HSQL Database Engine
  • DB2/NT
  • Informix Dynamic Server 
  • FrontBase

73. What is @Transient in Hibernate? 

@Transient is one of the Object states. In hibernate which is object relation mapping, it will map or create every variable with the class we have defined.  

74. What are callback interfaces in hibernate? 

Callback interfaces of hibernate are useful in receiving event notifications from objects. For example, when an object is loaded or deleted, an event is generated and notification is sent using callback interfaces. 

75. What is a pure relational ORM property in hibernate? 

In a pure relational object-relational mapping entire application, including the user interface, is designed around the relational model and SQL-based relational operations. 

Top Hibernate Interview Questions And Answers

76. What are the Extension interfaces of hibernate framework?  

There are many extension interfaces provided by hibernate.

  • ProxyFactory interface: For create proxies
  • TransactionFactory interface: For transaction management 
  • ConnectionProvide interface: For JDBC connection management 
  • Transaction interface: For transaction management 
  • TransactionManagementLookup interface: For transaction management
  • Cache interface: It provides caching techniques and strategies
  • CacheProvider interface: same as Cache interface
  • ClassPersister interface: It provides ORM strategies
  • IdentifierGenerator interface: For primary key generation
  • Dialect abstract class: It provides SQL support

77. How can we hibernate session factory to JNDI? 

Hibernate session factory can be bound to JNDI by making configuration changes in hibernate.cfg.file.

78. What are the types of Hibernate instance states? 

Three types of instance states:

  • Transient: The instance is not associated with any persistence context
  • Persistent: The instance is associated with a persistence context
  • Detached: The instance was associated with a persistence context which has been closed or currently not associated. 

79. What is the main difference between spring and hibernate?

Spring and Hibernate are two different things, Spring has several components like Dependency Injection, Spring MVC, Spring ORM, Spring Rest API. 

So Spring ORM and Hibernate are kind of similar, they both deal with the object relation model, which means they deal with connection java objects to database entities. 

Now if you want to build a Rest API using Spring Rest API for ORM you can either choose Hibernate or Spring ORM framework, in either case, there are advantages and disadvantages but major industry goes with using Hibernate. 

80. Which annotation should be used to declare a class in Hibernate bean?

We can use @Entity annotation to declare a class as an entity.

Example: 


@Entity
@Table(name=”post”)
public class Post{String title; String description;}

81. What is Lazy loading in Hibernate? 

In Lazy loading, we can load objects on a requirement basis.

Lazy loading is by default enabled from Hibernate 3.0 so that the child objects are not charged while the parent is loaded. 

82. What are inheritance Mapping Strategies available? 

Hibernate has three ways of inheritance mapping, as listed below: 

  • Table per concrete class
  • Table per hierarchy 
  • Table per subclass

83. Describe the criteria object in Hibernate. 

We can use criteria objects to create and execute object-oriented queries to retrieve the object. 

84. Explain the Session object in Hibernate. 

It is used to get a connection with a database. A session object is created to instantiate an interaction with a database, whereas the persistent objects are retrieved using a session object. The session objects are not thread-safe so that they can be created and destroyed as per the requirement.   

85. What is the use of Hibernate Session merge() call? 

We can use the Hibernate Session merge() to update existing values; however, this method creates a copy from the passed entity object and returns it. The returned object is part of the persistent context and tracked for any changes; the given object is not tracked. For example, a program, read hibernate merge. 

86. What will happen if a user doesn’t have a no-args constructor in Entity bean? 

Hibernator uses Reflection API to create an instance of Entity beans while calling get() or load() method. The method Class.newInstance() is used for this, and it requires a no-args constructor. So if you don’t have a no-args constructor in entity beans, Hibernate will fail to instantiate it, and you will get HibernateException. 

87. How to implement relationships in Hibernate? 

We can quickly implement relationships like One to One Mapping, One to Many Mapping, and Many to Many mapping using JPA annotations as well as XML based configurations. 

88. How to use JNDI DataSource with the Hibernate framework? 

It’s always useful to allow a servlet container to manage the connection pool as the user so that we define JNDI resource for DataSource, and we can use it in the web application. It’s straight word to use in Hibernate, all we need is to remove all the database-specific properties and use the below feature to provide the JNDI Datasource name. 

Example:

<property name=”hibernate.connection.datasource”>java:comp/env/jdbc/MyLocalDB</property>

89. What are the benefits of the Hibernate Tools Eclipse plugin? 

Hibernate tools plugin helps the users in writing hibernate configuration and mapping files quickly. The primary benefit is the content assists in assisting the user with different properties and XML tags to use. It validates them against the Hibernate DTD files, so the user knows any mistakes beforehand. 

90. Explain the key components used in Hibernate. 

The key component of Hibernate are as described below: 

  • Session: Session is used to get a physical network with a database.
  • Query: It uses SQL and HQL string to retrieve the data from the database and create objects. 
  • Transaction: Transaction represents the unit of work with a database. 
  • Criteria: The primary use of criteria is to create and execute object-oriented queries and retrieve the objects.
  • Configuration: It represents the properties of files required by Hibernate.
  • Session Factory: It configures hibernate for the application using the provided configuration file and instantities the session object. 

91. Should we make Entity class final or not? If not, then why?  

Hibernate uses a proxy class for the lazy loading of data, and it can be done by extending the entity bean if we finalize lazy loading. Lazy loading won’t be possible, hence low performance. 

92. Is the Session Factory of Hibernate thread-safe ?

The session factory of Hibernate is thread-safe because the internal state of SessionFactory is immutable, and multiple threads can access SessionFactory is immutable, and Multiple threads can access Session factory simultaneously to get Session instances.

93. What is the Hibernate configuration file?   

It is the file that contains information to establish a connection with database software and to provide instructions to Hibernate Framework. 

This file contains three types of details: 

  • Connection Properties
  • Hibernate Properties
  • Hibernate mapping file names.

94. What are the three core concepts used in the Hibernate framework?  

  • Configuration: When Hibernate configuration object is created, Hibernate framework will be activated based on the jar file that is added to class path  or build path. This object also reads data and verifies given configuration file and mapping file entries and stores the information as “in-memory metadata” at RAM-Level in the form of HashMap object. 

Now onwards if configuration file, mapping file information required during execution of the application. It will connect from that “In-Memory metadata”(HashMap) instead of going to those physical XML files. 

Example:

//Activate Hibernate Framework

 //Verify and Read both configuration files, Mapping file data and store the data as in-memory metadata

 Final StandardServiceRegistry registry=new

StandardServiceRegistryBuilder().configure().build();   

  • SessionFactory: It will be created based on the StandardServiceRegistry object. This object holds connection properties, hibernate configuration file information, mapping file information and other details so it is called a heavy weight object in Hibernate programming. 

It is an immutable object i.e. once the data placed in that object it can not be modified.

It is a thread-safe object because all immutable objects are thread-safe objects by default. 

It is a factory to create hibernate Session objects. 

Example: 

SessionFactory sessionFactory = new

MetadataSources(registry).buildMetadata().buildSessionFactory();

  • Session: SessionFactory object gets one connection object from its JDBC connection pool and uses that object to create Hibernate Session Object. 

The object Open connection between Java application and Database software through Hibernate frameworks. 

It is the base object for programmers to give persistence instructions to hibernate framework using Domain class objects.

It is not a thread-safe object by default. 

Example: Session session = HibernateUtil.getSessionFactory().openSession();

95. What is a Hibernate dialect? 

It is an optional property of the Hibernate configuration file but it is a recommended property to use. It helps the Hibernate Framework to decide the destination Database Software to communicate. 

It helps hibernate framework to generate optimized SQL as required for underlying DB Software. 

<property name = “hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>

96. What is the difference between session.save() and session.persist() methods? 

Session.save()Session.persist()
It is used to return the generated identity value.It does not return the generated identity value because its return type is void.

Signatures: 

Public Seraizible save(Object obj);

Public void persist(Object obj);

97. What is the difference between session.load() and session.get() method? 

session.get()session.load()
Perform early/eager loadingPerform lazy loading 
Does not create any proxy objectIt will create a proxy object 
Create the only object for domain class to load a single recordIt will create two objects( Proxy + Read object) for the domain class to load a single record
Does not throw any exception if a record is not found It will throw an exception if a record is not found i.e ObjectNotFoundException
Suitable to check whether the record is available or not Not suitable to check whether a record is available or not. If sure about the record is available then only use 
Use this method when the loaded record will be used immediately Use this method when the loaded record will be used lately

98. What is the difference between session.save() or session.saveOrUpdate() methods? 

session.update()session.saveOrUpdate()
It is used to update the records by using SQL query It is used to update the record if the record is already available, otherwise, it will insert the record. For this, it internally generates a select query and insert/update query. 

99. What is the difference between session.saveOrUpdate() and session.merge() methods? 

session.saveOrUpdate()session.merge()
It does not return an object representing the record that will be inserted or updated because its return type is void. It returns an object representing the record that will be inserted/updated. 
If we call session.saveOrUpdate() to update the object with the same identity value that is already there in the first level cache of the session object then we will get Exception. (NonUniqueObjectException). If we call session.merge() to update the object with the same identity value that is already there in the first level cache of the session object then no exception will raise, moreover given object modification will be synchronized with database table records. 

Note: If you modify the same record by loading the record or object in multiple sessions then to merge all modifications and reflect the changes to the database table use session.merge() method. 

100. Why do we need the “hibernate.hbm2ddl.auto” property? 

Hibernate allows you to create/alter database tables based on configuration done in hibernate mapping files. 

This option is useful to add new columns in the middle of project development or in the production environment of the project. 

This property is also useful to create database tables dynamically. If the database is changed in the middle of project development or in the production environment dynamically.

It is recommended not to use this option to design the database table of a project because this will be taken care of by the database designing team before coding of the project.  

This property has four values: 

  • Create
  • Update
  • Validate(default)
  • Create-drop 

That’s all for Hibernate interview questions and answers.  All important interview questions and answers have been listed above. These interview questions will refresh your knowledge and will surely help crack your interview.