Blog

Blog

Top 50 Hibernate Interview Questions That Are A Must in 2023

Hibernate Interview Questions

Hibernate Interview Questions

1. What is Hibernate?

Hibernate - Hibernate Interview Questions- EdurekaHibernate is one of the most popular Java frameworks that simplify the development of Java application to interact with the database. It is an Object-relational mapping (ORM) tool. Hibernate also provides a reference implementation of Java API.

It is referred as a framework which comes with an abstraction layer and also handles the implementations internally. The implementations include tasks like writing a query for CRUD operations or establishing a connection with the databases, etc.

Hibernate develops persistence logic, which stores and processes the data for longer use. It is a lightweight tool and most importantly open-sourced which gives it an edge over other frameworks.

2. What are the major advantages of Hibernate Framework? 

  1. Efficient data access: Hibernate provides a high-level object-oriented interface for interacting with a database, which can be more efficient and easier to use than traditional SQL queries.
  2. Improved performance: Hibernate can improve the performance of your application by providing efficient caching mechanisms and lazy loading of data.
  3. Reduced development time: Hibernate simplifies the development process by providing a simple, easy-to-use API and by eliminating the need to write boilerplate code for data persistence and object-relational mapping.
  4. Improved portability: Hibernate is database independent, which means that you can easily switch between different databases without having to change your code.
  5. Supports various database models: Hibernate supports a wide range of databases, including MySQL, Oracle, and PostgreSQL.
  6. Scalability: Hibernate is designed to scale well, so it can handle large volumes of data without performance degradation.
  7. Improved maintainability: Hibernate provides a clear separation between the application code and the data persistence layer, which can make it easier to maintain and update your application over time.

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

Major advantages of using Hibernate over JDBC are:

  1. Hibernate eliminates a lot of boiler-plate code that comes with JDBC API, the code looks cleaner and readable.
  2. This Java framework supports inheritance, associations, and collections. These features are actually not present in JDBC.
  3. HQL (Hibernate Query Language) is more object-oriented and close to Java. But for JDBC, you need to write native SQL queries.
  4. Hibernate implicitly provides transaction management whereas, in JDBC API, you need to write code for transaction management using commit and rollback.
  5. JDBC throws SQLException that is a checked exception, so you have to write a lot of try-catch block code. Hibernate wraps JDBC exceptions and throw JDBCException or HibernateException which are the unchecked exceptions, so you don’t have to write code to handle it has built-in transaction management which helps in removing the usage of try-catch blocks.

4. What is an ORM tool?

It is basically a technique that maps the object that is stored in the database. An ORM tool helps in simplifying data creation, manipulation, and access. It internally uses the Java API to interact with the databases.

image 46

5. Why use Hibernate Framework?

Hibernate overcomes the shortcomings of other technologies like JDBC.

  • It overcomes the database dependency faced in the JDBC.
  • Changing of the databases cost a lot working on JDBC, hibernate overcomes this problem with flying colors.
  • Code portability is not an option while working on JDBC. This is easily handled by Hibernate.
  • Hibernate strengthens the object level relationship.
  • It overcomes the exception-handling part which is mandatory while working on JDBC.
  • It reduces the length of code with increased readability by overcoming the boilerplate problem.

6. What are the different functionalities supported by Hibernate?

  • Hibernate is an ORM tool.
  • Hibernate uses Hibernate Query Language(HQL) which makes it database-independent.
  • It supports auto DDL operations.
  • This Java framework also has an Auto Primary Key Generation support.
  • Supports cache memory.
  • Exception handling is not mandatory in the case of Hibernate.

7. What are the technologies that are supported by Hibernate?

Hibernate is a Java-based framework, so it can be used with any Java-based application. It is commonly used with Java EE and Java SE applications, but it can also be used with other technologies such as Java ME (Micro Edition).

Hibernate can be used with a wide range of databases, including popular open-source databases like MySQL, PostgreSQL, and Apache Derby, as well as commercial databases like Oracle, Microsoft SQL Server, and Sybase. It can also be used with NoSQL databases like MongoDB and Apache Cassandra.

In addition to databases, Hibernate can be used with various other technologies, such as JavaServer Pages (JSP), JavaServer Faces (JSF), and Java Servlets. It can also be integrated with popular Java-based application servers like Apache Tomcat and GlassFish.

8. What is HQL?

HQL stands for Hibernate Query Language. It is a powerful, object-oriented query language that is used to perform queries against a database in Hibernate.

HQL is similar to SQL, but it operates on objects and properties of persistent classes rather than on tables and columns of a database. This allows HQL to be more expressive and to provide a more natural way of querying data for developers who are familiar with object-oriented programming.

For example, the following HQL query selects all the records from the “Employee” table where the “salary” is greater than 10000:

Copy codeFROM Employee e WHERE e.salary > 10000

HQL also supports various operations such as insert, update, and delete, as well as complex queries with grouping, ordering, and aggregation functions.

HQL is an important feature of Hibernate that allows developers to easily query and manipulate data in a database using a simple, intuitive syntax.

9. How to achieve mapping in Hibernate?

In Hibernate, mapping is the process of defining how the data in a Java object should be persisted to and retrieved from a database. This is typically done using mapping metadata, which specifies how the data in the Java object should be mapped to the columns in a database table.

There are several ways to achieve mapping in Hibernate:

  1. Using XML mapping files: In this approach, the mapping metadata is defined in an XML file that is separate from the Java code. The XML file defines the mapping between the Java class and the database table, as well as the mapping between the class’s properties and the table’s columns.
  2. Using annotations: In this approach, the mapping metadata is defined using Java annotations in the source code of the persistent class. The annotations are added to the class and its properties, and they specify the mapping to the database table and columns.
  3. Using a combination of XML and annotations: It is also possible to use a combination of XML mapping files and annotations to define the mapping metadata. This allows you to use the benefits of both approaches and to separate the mapping metadata from the Java code.

Regardless of which approach is used, the mapping metadata is used by Hibernate to automatically generate the SQL statements needed to persist and retrieve data from the database. This can greatly simplify the data access layer of an application and improve its performance and maintainability.

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

Some of the important interfaces of the Hibernate framework are:

  1. Session: This interface is used to represent a single-threaded unit of work with the database. It provides methods for querying and manipulating data, as well as for managing transactions.
  2. SessionFactory: This interface is used to create Session objects. It is a heavyweight object that is typically created at application startup and is used to create Sessions throughout the lifetime of the application.
  3. Query: This interface represents a Hibernate query and provides methods for specifying query parameters and for executing the query.
  4. Criteria: This interface is used to create and execute criteria-based queries. It provides a more object-oriented way of specifying query criteria and is useful for building dynamic queries.
  5. Transaction: This interface represents a transaction and provides methods for starting, committing, and rolling back transactions.
  6. Configuration: This interface is used to configure Hibernate and to create a SessionFactory. It provides methods for specifying the database connection details, the mapping documents, and other configuration options.
  7. PersistentObject: This interface is implemented by all persistent classes in Hibernate. It defines the methods that are used by Hibernate to manage the persistent state of an object.

These are some of the most important interfaces in the Hibernate framework, but there are many others as well.

In this type of mapping,  you only need to model the system for the entity for which you want to navigate the relationship in your query or domain model. You need an entity attribute that represents the association, so annotate it with an @OneToOne annotation.

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

In this type of association, 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 that does not have any redundant element. This One-to-Many element of the set indicates the relation of one object to multiple objects.

13. What is 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. In Unidirectional, the attributes model the association and you can use it to navigate it in your domain model or JPQL queries. The annotation tells Hibernate to map a Many-to-Many association. The bidirectional relationship, mapping allows you to navigate the association in both directions. 

14. How to integrate Hibernate and Spring?

Spring is also one of the most commonly used Java frameworks in the market today. Spring is a JavaEE Framework and Hibernate is the most popular ORM framework. This is why Spring Hibernate combination is used in a lot of enterprise applications. 

Following are the steps you should follow to integrate Spring and Hibernate.

  1. Add Hibernate-entity manager, Hibernate-core and Spring-ORM dependencies.
  2. Create Model classes and corresponding DAO implementations for database operations. The DAO classes will use SessionFactory that will be injected by the Spring Bean configuration.
  3. Note that you don’t need to use Hibernate Transaction Management, as you can leave it to the Spring declarative transaction management using @Transactional annotation.

15. What do you mean by Hibernate Configuration File?

Hibernate Configuration File mainly contains database-specific configurations and are used to initialize SessionFactory. Some important parts of the Hibernate Configuration File are Dialect information, so that hibernate knows the database type and mapping file or class details.

Hibernate Interview Questions for intermediate

16. Mention some important annotations used for Hibernate mapping?

Hibernate supports JPA annotations. Some of the major annotations are:

  1. javax.persistence.Entity: This is used with model classes to specify they are entity beans.
  2. javax.persistence.Table: It is used with entity beans to define the corresponding table name in the database.
  3. javax.persistence.Access: Used to define the access type, field or property. The default value is field and if you want Hibernate to use the getter/setter methods then you need to set it to a property.
  4. javax.persistence.Id: Defines the primary key in the entity bean.
  5. javax.persistence.EmbeddedId: It defines a composite primary key in the entity bean.
  6. javax.persistence.Column: Helps in defining the column name in the database table.
  7. javax.persistence.GeneratedValue: It defines the strategy to be used for the generation of the primary key. It is also used in conjunction with javax.persistence.GenerationType enum.

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

Hibernate Session is the interface between Java application layer and Hibernate. It is used to get a physical connection with the database. The Session object created is lightweight and designed to be instantiated each time an interaction is needed with the database. This Session provides methods to create, read, update and delete operations for a constant object. To get the Session, you can execute HQL queries, SQL native queries using the Session object.

18. What is Hibernate SessionFactory?

In Hibernate, the SessionFactory is a factory class that is used to create Session objects. It is a heavyweight object that is typically created at application startup and is used to create Sessions throughout the lifetime of the application.

The SessionFactory is created using the Configuration object, which is used to specify the database connection details, the mapping documents, and other configuration options. Once the SessionFactory has been created, it can be used to create Session objects, which are used to perform the actual work with the database.

The SessionFactory is a thread-safe object that can be shared by multiple threads, so it is typically stored in a static field or in a singleton object. This allows it to be easily accessed by different parts of the application that need to perform database operations.

In addition to creating Session objects, the SessionFactory also provides methods for executing HQL queries and for performing other common database operations. It also manages the caching of persistent objects and the connection pool, which can improve the performance of the application.

Overall, the SessionFactory is an important part of the Hibernate framework and is used to manage the interaction between the application and the database.

19. What is the difference between openSession and getCurrentSession?

Here is a summary of the main differences between openSession and getCurrentSession:

openSessiongetCurrentSession
Creates new Session objectAlwaysOnly if needed
Session is thread-boundNoYes
Session must be closedYesNo
More flexibleYesNo

Here is a brief explanation of each difference:

  • Creates new Session object: openSession always creates a new Session object, regardless of whether a Session already exists for the current thread. getCurrentSession, on the other hand, creates a new Session object only if there is no existing Session bound to the current thread.
  • Session is thread-bound: openSession creates a Session that is not bound to the current thread, so it cannot be used in a thread-bound manner. getCurrentSession, on the other hand, creates a Session that is bound to the current thread and can be used in a thread-bound manner.
  • Session must be closed: openSession requires the developer to explicitly close the Session when it is no longer needed, using the close() method. getCurrentSession, on the other hand, closes the Session automatically at the end of the transaction, so the developer does not have to worry about closing it manually.
  • More flexible: openSession is more flexible than getCurrentSession, as it allows the developer to have more control over the Session and to use it in a non-thread-bound manner. getCurrentSession, on the other hand, is intended to be used in a thread-bound manner and is less flexible.

20. What do you mean by Hibernate configuration file?

The following steps help in configuring Hibernate file:

  1. First, identify the POJOs (Plain Old Java Objects) that have a database representation.
  2. Identify which properties of POJOs need to be continued.
  3. Annotate each of the POJOs in order to map the Java objects to columns in a database table.
  4. Create a database schema using the schema export tool which uses an existing database, or you can create your own database schema.
  5. Add Hibernate Java libraries to the application’s classpath.
  6. Create a Hibernate XML configuration file that points to the database and the mapped classes.
  7. In the Java application, you can create a Hibernate Configuration object that refers to your XML configuration file.
  8. Also, build a Hibernate SessionFactory object from the Configuration object.
  9. Retrieve the Hibernate Session objects from the SessionFactory and write down the data access logic for your application (create, retrieve, update, and delete).

Hibernate Interview Questions

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

  1. Database connection details: The Configuration object contains information about the database that Hibernate will be connecting to, such as the JDBC driver class, the URL, the username, and the password.
  2. Mapping documents: The Configuration object specifies the location of the mapping documents that define the mapping between the Java classes and the database tables. These documents can be in the form of XML files or annotations in the source code of the persistent classes.
  3. Caching settings: The Configuration object can be used to specify the caching settings for the application, such as the type of cache to use (e.g. first-level cache, second-level cache), the cache provider, and the cache region.
  4. Transaction settings: The Configuration object can be used to specify the transaction settings for the application, such as the transaction factory, the transaction manager, and the transaction isolation level.
  5. SQL dialect: The Configuration object specifies the SQL dialect that Hibernate should use when generating SQL statements. This allows Hibernate to generate SQL that is optimized for the specific database that it is connecting to.
  6. Other settings: The Configuration object also includes various other settings that can be used to customize the behavior of Hibernate, such as the JDBC batch size, the default entity mode, and the default flush mode.

Overall, the Configuration object is an important part of the Hibernate framework, as it provides a central place to configure and customize the behavior of Hibernate.

22. Discuss the Collections in Hibernate

Hibernate provides the facility to persist the Collections. A Collection basically can be a List, Set, Map, Collection, Sorted Set, Sorted Map. java.util.List, java.util.Set, java.util.Collection, etc, are some of the real interface types to declared the persistent collection-value fields. Hibernate injects persistent Collections based on the type of interface. The collection instances generally behave like the types of value behavior.

23. What are the collection types in Hibernate?

There are five collection types in hibernate used for one-to-many relationship mappings.

  1. Set: A set is a collection of unique elements that are stored in an unordered manner. Sets are implemented using a hash table and do not allow duplicate elements.
  2. List: A list is an ordered collection of elements that allows duplicate elements. Lists are implemented using an array or a linked list, and the elements are stored in the order in which they are added.
  3. Map: A map is a collection of key-value pairs that are stored in an unordered manner. Maps are implemented using a hash table and do not allow duplicate keys.
  4. Array: An array is a collection of elements that are stored in an ordered manner and that have a fixed size. Arrays are implemented using a contiguous block of memory and can be used to represent one-to-many relationships.
  5. Bag: A bag is a collection of elements that allows duplicate elements and that is stored in an unordered manner. Bags are implemented using a list or an array, and they do not maintain the order of the elements.

These are some of the main collection types in Hibernate, but there are others as well. Each type of collection is suitable for different types of relationships and has its own set of characteristics and performance trade-offs.

24. What is a Hibernate Template class?

When you integrate Spring and Hibernate, Spring ORM provides two helper classes – HibernateDaoSupport and HibernateTemplate. The main reason to use them was to get two things, the Session from Hibernate and Spring Transaction Management. However, from Hibernate 3.0.1, you can use the SessionFactory getCurrentSession() method to get the current session. The major advantage of using this Template class is the exception translation but that can be achieved easily by using @Repository annotation with service classes.

25. What are the benefits of using Hibernate template?

The following are the benefits of using this Hibernate template class:

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

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

There are a few design patterns used in Hibernate Framework, namely:

  • Domain Model Pattern: An object model of the domain that incorporates both behavior as well as data.
  • Data Mapper: A layer of the map that moves data between objects and a database while keeping it independent of each other and the map itself.
  • Proxy Pattern: It is used for lazy loading.
  • Factory Pattern: Used in SessionFactory.

27. Define Hibernate Validator Framework

Data validation is considered as an integral part of any application. Also, data validation is used in the presentation layer with the use of Javascript and the server-side code before processing. It occurs before persisting it in order to make sure it follows the correct format. Validation is a cross-cutting task, so we should try to keep it apart from the business logic. This Hibernate Validator provides the reference implementation of bean validation specs.

28. What is Dirty Checking in Hibernate?

Hibernate incorporates Dirty Checking feature that permits developers and users to avoid time-consuming write actions. This Dirty Checking feature changes or updates fields that need to be changed or updated, while keeping the remaining fields untouched and unchanged.

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

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

30. What is meant by Light Object Mapping?

The means that the syntax is hidden from the business logic using specific design patterns. This is one of the valuable levels of ORM quality and this Light Object Mapping approach can be successful in case of applications where there are very fewer entities, or for applications having data models that are metadata-driven.

Hibernate Interview Questions for experienced

31. What is meant by Hibernate tuning?

Hibernate tuning refers to the process of optimizing the performance of a Hibernate-based application by adjusting various configuration parameters and settings. Hibernate tuning is an important aspect of building and maintaining a high-performance application, as it can have a significant impact on the performance and scalability of the application.

There are many different aspects of Hibernate that can be tuned, including the database connection pool, the caching settings, the transaction settings, and the SQL generation settings. Each of these aspects can be adjusted to optimize the performance of the application for different workloads and usage patterns.

Some common Hibernate tuning techniques include:

  1. Enabling caching: Enabling caching can improve the performance of Hibernate by reducing the number of database queries that are required to retrieve data.
  2. Adjusting the batch size: Adjusting the batch size can improve the performance of Hibernate by reducing the number of round trips to the database that are required to insert or update data.
  3. Tuning the connection pool: Tuning the connection pool can improve the performance of Hibernate by ensuring that there are enough connections available to meet the needs of the application and by minimizing the overhead of creating and closing connections.
  4. Optimizing the SQL generation: Optimizing the SQL generation can improve the performance of Hibernate by generating more efficient SQL statements that are optimized for the specific database that is being used.

Overall, Hibernate tuning is an important aspect of building and maintaining a high-performance application, and it can involve a wide range of techniques and strategies depending on the specific needs and requirements of the application.

32. What is Transaction Management in Hibernate? How does it work?

Transaction Management is a property which is present in the Spring framework. Now, what role does it play in Hibernate?

Transaction Management is a process of managing a set of commands or statements. In hibernate, Transaction Management is done by transaction interface. It maintains abstraction from the transaction implementation (JTA, JDBC). A transaction is associated with Session and is instantiated by calling session.beginTransaction().

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

You can integrate any Struts application with Hibernate. There are no extra efforts required.

  1. Register a custom ServletContextListener.
  2. In the ServletContextListener class, first, initialize the Hibernate Session, store it in the servlet context.
  3. Action class helps in getting the Hibernate Session from the servlet context, and perform other Hibernate task as normal.

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

It may exist in one of the following 3 states:

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

35. 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. The generator can also be used to specify how a Primary key can be created in the database.

1234<id name="ClassID"type="string"><column name= "columnID"length="10"><generator/></id>

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

  • Hibernate uses a proxy object in order to support Lazy loading.
  • When you try loading data from tables, Hibernate doesn’t load all the mapped objects.
  • After you reference a child object through getter methods, if the linked entity is not present in the session cache, then the proxy code will be entered to the database and load the linked object.
  • It uses Java assist to effectively and dynamically generate sub-classed implementations of your entity objects.

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

To see the Hibernate-generated SQL on the console, you can use the following steps:

  1. Open the Hibernate configuration file (e.g. hibernate.cfg.xml) and add the following property to the <properties> element:
Copy code<property name="show_sql">true</property>

This property tells Hibernate to log all the SQL statements that it generates to the console.

  1. Alternatively, you can enable the SQL logging feature programmatically by adding the following line of code to your application:
Copy codeLogger.getLogger("org.hibernate").setLevel(Level.DEBUG);

This will enable the SQL logging feature for all the Hibernate sessions in your application.

  1. Start your application and perform the actions that trigger the execution of Hibernate-generated SQL statements.
  2. The generated SQL statements will be logged to the console and will be displayed in the console output.

Note that you can also use a logger configuration file (e.g. log4j.properties) to control the logging levels and output destinations for the Hibernate-generated SQL statements. This can be useful if you want to log the SQL statements to a file or to a separate log appender.

38. What is Query Cache in Hibernate?

In Hibernate, the query cache is a second-level cache that is used to cache the results of HQL and Criteria queries. When a query is executed, the results are stored in the query cache along with the query parameters. If the same query is executed again with the same parameters, the results can be retrieved from the cache, which can greatly improve the performance of the application.

The query cache is implemented using a hash table, and it stores the results of the queries as a key-value pair, where the key is the query and the parameters and the value is the query results.

To use the query cache, you need to enable it in the Hibernate configuration file (e.g. hibernate.cfg.xml) by adding the following property:

Copy code<property name="cache.use_query_cache">true</property>

You can also enable the query cache programmatically by calling the following method:

Copy codesessionFactory.getCache().setQueryCacheEnabled(true);

Once the query cache is enabled, you can use the setCacheable() method of the Query object to specify whether a particular query should be cached or not. For example:

Copy codeQuery query = session.createQuery("FROM Employee e WHERE e.salary > :salary");
query.setCacheable(true);
query.setParameter("salary", 10000);

The query cache is an important feature of Hibernate that can greatly improve the performance of the application by reducing the number of database queries that are required to retrieve data. However, it is important to carefully consider the trade-offs between the performance benefits of the query cache and the added complexity and overhead of maintaining it.

39. 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 SQLQuery object. For normal scenarios, it is however not the recommended approach because you might lose other benefits like Association and Hibernate first-level caching.

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

40. What is Named SQL Query?

Hibernate provides another important feature called Named Query using which you can define at a central location and use them anywhere in the code.

You can create named queries for both HQL as well as for Native SQL. These Named Queries can be defined in Hibernate mapping files with the help of JPA annotations @NamedQuery and @NamedNativeQuery.

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

In Hibernate, the merge() and update() methods are used to update the state of a detached object and to synchronize it with the state of a persistent object in the database.

The merge() method is used to copy the state of a detached object into a persistent object and to return the persistent object. The persistent object is then associated with the current Hibernate session and can be persisted or updated in the database. The detached object, on the other hand, is not associated with the current session and is not modified.

The update() method, on the other hand, is used to update the state of a persistent object in the database with the state of a detached object. The detached object is not modified, but the persistent object is updated with the new state.

Here is an example of how to use the merge() method:

Copy codeDetachedObject detachedObject = new DetachedObject();
// set the state of the detached object

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

PersistentObject persistentObject = (PersistentObject) session.merge(detachedObject);
// the persistent object is now associated with the current session and can be persisted or updated

session.getTransaction().commit();
session.close();

Here is an example of how to use the update() method:

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

Here is a table that summarizes the main differences between the get() and load() methods in Hibernate:

MethodDescription
get()This method retrieves a persistent object from the database using the primary key. If the object is not found, it returns null. This method always hits the database to get the object.
load()This method also retrieves a persistent object from the database using the primary key. However, it returns a proxy object that represents the object. The actual object is only loaded from the database when it is needed (e.g., when a method of the object is invoked). If the object is not found, load() throws a ObjectNotFoundException. This method does not hit the database until the object is actually needed.

It’s worth noting that load() can be more efficient than get() in cases where the object may not be needed (e.g., if you are just checking if an object exists). However, it is less safe to use because it can throw an exception if the object is not found, and it requires that the object exists in the database. get(), on the other hand, is safer to use because it simply returns null if the object is not found, and it does not require that the object exists in the database.

43. Difference between the first and second level cache in Hibernate? 

In Hibernate, the first-level cache (also called the session-level cache) is the cache of persistent objects that are associated with a particular Session. Every Session has its own first-level cache, which means that the cache is not shared across different Session objects.

The second-level cache (also called the session-factory-level cache) is a cache that is shared across all Session objects that are created from the same SessionFactory. The second-level cache is optional and must be explicitly enabled in the configuration.

Here is a summary of the main differences between the first-level and second-level caches:

First-level cacheSecond-level cache
Associated with a particular SessionShared across all Session objects created from the same SessionFactory
Not shared across different Session objectsShared across different Session objects
Automatically enabledMust be explicitly enabled in the configuration
Only stores persistent objectsCan store other things, such as query results and collection mappings
Only lasts for the duration of the SessionCan be configured to last longer than the Session

It’s worth noting that both the first-level and second-level caches can significantly improve the performance of a Hibernate application by reducing the number of database hits. However, they can also increase the complexity of the application because you have to carefully manage the cache to ensure that it is consistent with the underlying database.

44. Difference between Session and SessionFactory in Hibernate?

In Hibernate, a Session represents a single-threaded unit of work with the database. It is used to create, read, update, and delete persistent objects, and to execute queries and native SQL statements. A Session is created by a SessionFactory, which is a thread-safe object that is used to create Session objects.

Here is a summary of the main differences between a Session and a SessionFactory:

SessionSessionFactory
Represents a single-threaded unit of work with the databaseCreates Session objects and is used to configure Hibernate
Used to create, read, update, delete persistent objects, and to execute queries and native SQL statementsThread-safe and can be shared by multiple Session objects
Not thread-safe and should not be shared by multiple threadsThread-safe and can be shared by multiple threads
Short-lived and should be created and closed for each unit of workLong-lived and should be created once and reused for the lifetime of the application

It’s worth noting that the SessionFactory is a heavyweight object and creating it can be expensive. Therefore, it is recommended to create a SessionFactory only once and reuse it for the lifetime of the application. The Session objects, on the other hand, are lightweight and should be created and closed for each unit of work.

45. Difference between save() and saveOrUpdate() method of Hibernate?

In Hibernate, the save() method is used to persist a new transient object to the database. It generates a new identifier for the object and assigns it to the object’s identifier property. The save() method returns the generated identifier.

The saveOrUpdate() method, on the other hand, is used to either save a new transient object or update a detached object. If the object is a new transient object, saveOrUpdate() behaves like save() and generates a new identifier for the object. If the object is a detached object, saveOrUpdate() updates the state of the object in the database.

Here is a summary of the main differences between the save() and saveOrUpdate() methods:

save()saveOrUpdate()
Persists a new transient object to the databaseCan either save a new transient object or update a detached object
Generates a new identifier for the objectIf the object is a new transient object, generates a new identifier for the object
Returns the generated identifierDoes not return anything

It’s worth noting that the saveOrUpdate() method can be more convenient to use than the save() method in cases where you are not sure if the object is new or detached. However, it can be less efficient because it requires an additional check to determine whether the object is new or detached. The save() method, on the other hand, is more efficient because it only performs the save operation, but it can only be used with new transient objects.

46. Difference between sorted and ordered collection in Hibernate?

In Hibernate, a sorted collection is a collection (e.g., a Set, List, or Map) that is sorted according to the natural order of its elements, or according to a Comparator that is provided by the application. A sorted collection is persisted in the same order in which it is sorted in memory.

An ordered collection, on the other hand, is a collection that has a specific order that is defined by the position of its elements. An ordered collection is persisted in the same order in which it is defined in the mapping.

Here is a summary of the main differences between a sorted and an ordered collection:

Sorted collectionOrdered collection
Sorted according to the natural order of its elements or according to a Comparator provided by the applicationHas a specific order that is defined by the position of its elements
Persisted in the same order in which it is sorted in memoryPersisted in the same order in which it is defined in the mapping
Can be used with any type of collection (e.g., Set, List, Map)Can only be used with List and Map collections

It’s worth noting that both sorted and ordered collections can be useful in different situations. A sorted collection can be useful when you want to sort the collection according to a specific criterion that is not reflected in the database, whereas an ordered collection can be useful when you want to preserve the specific order of the elements in the collection.

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

Transient state: New objects are created in the Java program but are not associated with any Hibernate Session.

Persistent state: An object which is associated with a Hibernate session is called Persistent object. While an object which was earlier associated with Hibernate session but currently it’s not associate is known as a detached object. You can call save() or persist() method to store those object into the database and bring them into the Persistent state.

48. Difference between managed associations and Hibernate associations?

In Hibernate, a managed association is an association between two persistent objects that is managed by the Session. A managed association is created when one persistent object is associated with another persistent object using a set method, and the association is persisted to the database when the transaction is committed.

Hibernate associations, on the other hand, are associations between two persistent objects that are defined in the mapping file. Hibernate associations can be one-to-one, one-to-many, many-to-one, or many-to-many. They are used to specify how the objects are related to each other in the database.

Here is a summary of the main differences between managed associations and Hibernate associations:

Managed associationHibernate association
Created when one persistent object is associated with another persistent object using a set methodDefined in the mapping file
Persisted to the database when the transaction is committedUsed to specify how the objects are related to each other in the database
Only exists for the duration of the SessionPersisted in the database and can outlast the Session

It’s worth noting that managed associations and Hibernate associations can be used together in a Hibernate application. Managed associations are useful for creating and modifying associations between persistent objects, whereas Hibernate associations are useful for specifying how the objects are related to each other in the database.

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

  • All Java classes that will be persisted need a default constructor.
  • All classes should contain an ID in order to allow easy identification of your objects within Hibernate and the database. This property maps to the primary key column of a database table.
  • All attributes that will be persisted should be declared private and have getXXX and setXXX methods defined in the JavaBean style.
  • A central feature of Hibernate, proxies, depends upon the persistent class being either non-final, or the implementation of an interface that declares all public methods.
  • All classes that do not extend or implement some specialized classes and interfaces required by the EJB framework.

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

  • Always check the primary key field access, if it’s generated at the database layer then you should not have a setter for this.
  • By default hibernate set the field values directly, without using setters. So if you want Hibernate to use setters, then make sure proper access is defined as @Access(value=AccessType.PROPERTY).
  • If access type is property, make sure annotations are used with getter methods and not setter methods. Avoid mixing of using annotations on both filed and getter methods.
  • Use native sql query only when it can’t be done using HQL, such as using the database-specific feature.
  • If you have to sort the collection, use ordered list rather than sorting it using Collection API.
  • Use named queries wisely, keep it at a single place for easy debugging. Use them for commonly used queries only. For entity-specific query, you can keep them in the entity bean itself.
  • For web applications, always try to use JNDI DataSource rather than configuring to create a connection in hibernate.
  • Avoid Many-to-Many relationships, it can be easily implemented using bidirectional One-to-Many and Many-to-One relationships.
  • For collections, try to use Lists, maps and sets. Avoid array because you don’t get benefit of lazy loading.
  • Do not treat exceptions as recoverable, roll back the Transaction and close the Session. If you do not do this, Hibernate cannot guarantee that the in-memory state accurately represents the persistent state.
  • Prefer DAO pattern for exposing the different methods that can be used with entity bean
  • Prefer lazy fetching for associations
Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
Click outside to hide the comparison bar
Compare

Subscribe to Newsletter

Stay ahead of the rapidly evolving world of technology with our news letters. Subscribe now!