Hibernate Interview Questions and answers for Freshres-Exp

1. What is Hibernate Framework?
Answer: Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is a java based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa.
Hibernate provides a reference implementation of the Java Persistence API, that makes it a great choice as an ORM tool with benefits of loose coupling. We can use the Hibernate persistence API for CRUD operations. Hibernate framework provides the option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration.
Similarly, hibernate configurations are flexible and can be done from XML configuration file as well as programmatically. For a quick overview of hibernate framework usage, you can go through the Hibernate Beginners Tutorial.

2. What is hibernate mapping file?
Answer: 
Hibernate mapping file is used to define the entity bean fields and database table column mappings. We know that JPA annotations can be used for mapping but sometimes XML mapping file comes handy when we are using third party classes and we can’t use annotations.

3. What is Hibernate Session and how to get it?
Answer: 
Hibernate Session is the interface between the java application layer and hibernate. This is the core interface used to perform database operations. The lifecycle of a session is bound by the beginning and end of a transaction.

The session provides methods to perform create, read, update and delete operations for a persistent object. We can execute HQL queries, SQL native queries and create criteria using Session object.

4. Hibernate Session is thread-safe?
Answer: 
Hibernate Session object is not threaded safe, every thread should get its own session instance and close it after it’s work is finished.

5. What will happen if we don’t have no-args constructor in Entity bean?
Answer: 
Hibernate uses Reflection API to create an instance of Entity beans, usually when you call get() or load() methods. (E learning Portal) The method Class.newInstance() is used for this and it requires no-args constructor. So if you won’t have no-args constructor in entity beans, hibernate will fail to instantiate it and you will get HibernateException.

6. How to implement Joins in Hibernate?
Answer: 
There are various ways to implement joins in hibernate.

Using associations such as one-to-one, one-to-many, etc.
Using JOIN in the HQL query. There is another form “join fetch” to load associated data simultaneously, no lazy loading.
We can fire a native sql query and use the join keyword.

7. What is the HibernateTemplate class?
Answer: 
When Spring and Hibernate integration started, Spring ORM provided two helper classes – HibernateDaoSupport and HibernateTemplate. The reason to use them was to get the Session from Hibernate and get the benefit of Spring transaction management. However, from Hibernate 3.0.1, we can use SessionFactory get current session() method to get the current session and use it to get the spring transaction management benefits. If you go through the above examples, you will see how easy it is and that’s why we should not use these classes anymore.

One other benefit of HibernateTemplate was exception translation but that can be achieved easily by using @Repository annotation with service classes, shown in above spring MVC example. This is a trick question to judge your knowledge and whether you are aware of recent developments or not.

8. What are the states of the object in hibernate?
Answer: 
There are 3 states of the object (instance) in hibernate.
1. Transient: The object is in a transient state if it is just created but has no primary key (identifier) and not associated with a session.
2. Persistent: The object is in a persistent state if a session is open, and you just saved the instance in the database or retrieved the instance from the database.
3. Detached: The object is in a detached state if a session is closed. After detached state, the object comes to persistent state if you call lock() or update() method.

9.Difference between get() vs load() method in Hibernate?
Answer: 
The key contrast amongst getting () and load() technique is that load() will throw an exception if id passed to them aren’t found, however, get() will return null. Another imperative distinction is that load can return intermediary without hitting the database unless required (when you get to any characteristic other than id) yet get() dependably go to the database, so once in a while utilizing load() can be quicker than the get() technique. It bodes well to utilize the load() technique on the off chance that you know the question exists yet to get() strategy if you don’t know about the object’s presence.

10. What is the difference between save() and persist() method in Hibernate?
Answer: 
The foremost difference between save() and persist() system is that save returns the result of a Serializable object while the return type of persisting () system is void, so it doesn’t yield anything as such.

11. What is lazy loading in hibernate and how is it done?
Answer:
Lazy fetching decides whether to load child objects while loading the Parent Object.

You need to do this setting respective hibernate mapping file of the parent class.
Lazy = true (means not to load child)
By default the lazy loading of the child objects is true. This makes sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case, hibernate issues a fresh database call to load the child when getChild() is actually called on the Parent object. But in some cases, you do need to load the child objects when a parent is loaded.
Just make the lazy=false and hibernate will load the child when the parent is loaded from the database.

12. Explain the mechanism by which you can distinguish between transient (i.e. newly instantiated) and detached objects in Hibernate?
Answer:
Hibernate uses the “version” property if there is one. If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys. You can create your own strategy with Interceptor.isUnsaved( ). When you reattach detached objects, you need to make sure that the dependent objects are reattached as well.

13. What is the need for hibernating tools when ORM tools can be used?
Answer:
The use of hibernate tools is to allow the programmer to code efficiently and saves them from being involved with the SQL code directly. It is used to increase the productivity of the work and uses high-level object-oriented APIs to increase the efficiency and performance of the work. It allows the programming to be more objects oriented and the code in Java has to be written less. It also saves programmers time to write the SQL code as there is no need to write the SQL code in it. These tools provide a very good caching system that keeps all the files and they provide it when it is required. It allows easy maintenance of the overall system and the code that is being written in it.

14. What is the role played by the SessionFactory interface in Hibernate?
Answer:
The session instance is being obtained by the application from Session Factory. It keeps the session instances at one place for easy access and dynamic allocation of the resources. There is always a single SessionFactory created for the complete application. This is created during the application initialization. It creates the cache that is used to generate the SQL statements and metadata information about the mapping of the Hibernate functions that gets used in run time. It holds the data that has been cached and then read into it. It focuses on reusability of the work and the functions that are stored in the Session Factory. This is represented as :

Session Factory session Factory = configuration.build SessionFactory.

15. Why Hibernate is preferred over JDBC?
Answer:
The preference of Hibernate is more due to the transparency it provides to the programmer for writing their code. It doesn’t allow the programmer to write explicit code to map the database tables to the application objects that are used during the interaction with RDBMS. It provides an advanced ORM solution to map the Java class files to the database tables for easy access and retrieval of the data. Hibernate uses Hibernate Query Language that is independent of the type of database used. It allows polymorphic queries to be retrieved and selects the way to perform the database manipulation tasks. Hibernate allows the storing of a large amount of data in small files that can be easily accessed and the performance can be faster. It also provides the actually mapping to be performed between the tables and objects in the XML files.

16. Why are callback interfaces useful in Hibernate?
Answer:
Callback interfaces are useful as it allows the application to receive important notification about the objects that are in the execution phase. It includes the objects that are loaded, saved or deleted from the Hibernate. Callback interfaces are very important to implement the general functionality like audit records, etc. It sends a notification when any object even occurs. It allows the programmer to get the error information or exception handling can be done in a better way to notify the user on run time in case of any problem in the programming code.

17. What are different states of an entity bean?
Answer:
An entity bean instance can exist is one of the three states.

Transient: When an object is never persisted or associated with any session, it’s in transient state. Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete().

Persistent: When an object is associated with a unique session, it’s in a persistent state. Any instance returned by a get() or load() method is persistent.

Detached: When an object is previously persistent but not associated with any session, it’s in a detached state. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().

18. What is the use of Hibernate Session merge() call?
Answer:
Hibernate merge can be used to update existing values, however, this method creates a copy from the passed entity object and return it. The returned object is part of the persistent context and tracked for any changes, passed object is not tracked. For example, program, read Hibernate merge.

19. What is the difference between Hibernate Session get () and load () method?
Answer:
Hibernate session comes with different methods to load data from the database. get and load is the most used methods, at first look, they seem similar but there are some differences between them.

get() loads the data as soon as it’s called whereas loading () returns a proxy object and loads data only when it’s actually required, so load() is better because it supports lazy loading.

Since load() throws an exception when data is not found, we should use it only when we know data exists.

We should use get() when we want to make sure data exists in the database.

For clarification regarding the differences, please read Hibernate get vs load.

20. What is HQL (Hibernate Query Language)?
Answer: Hibernate Query Language is known as an object-oriented query language. It is like a structured query language (SQL).

The main advantage of HQL over SQL is:
1. You don’t need to learn SQL
2. Database independent
3. Simple to write a query

  1. What are the benefits of Hibernate over JDBC?
    Answer:
    Other than a good persistence i.e. saving as well as loading the data from a given Database, Hibernate also offer the following aids

Caching
Lazy Loading
The developer is absolutely free from scripting code to either load or store data into the database.
Good relationship management and offers code for mapping an object right to the data.

  1. How to integrate Hibernate and Spring frameworks?
    Answer: Spring is one of the most used Java EE Framework and Hibernate is the most popular ORM framework. That’s why Spring Hibernate combination is used a lot in enterprise applications. The best part of using Spring is that it provides out-of-box integration support for Hibernate with Spring ORM module. Following steps are required to integrate Spring and Hibernate frameworks together.

Add hibernate-entitymanager, hibernate-core and spring-orm dependencies.
Create Model classes and corresponding DAO implementations for database operations. Note that DAO classes will use SessionFactory that will be injected by Spring Bean configuration.
If you are using Hibernate 3, you need to configure org.springframework.orm.hibernate3.LocalSessionFactoryBean or org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean in Spring Bean configuration file. For Hibernate 4, there are single class org.springframework.orm.hibernate4.LocalSessionFactoryBean that should be configured.
Note that we don’t need to use Hibernate Transaction Management, we can leave it to Spring declarative transaction management using @Transactional annotation.
For complete example go through Spring Hibernate Integration and Spring MVC Hibernate Integration.

  1. What are the best practices to follow with Hibernate framework?
    Answer:
    Some of the best practices to follow in Hibernate are:

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 to hibernate to use setters, then make sure proper access is defined as @Access(value=AccessType.PROPERTY).
If the 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 the 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

  1. What is Hibernate Validator Framework?
    Answer:
    Data validation is an integral part of any application. You will find data validation at the presentation layer with the use of Javascript, then at the server-side code before processing it. (Company) Also, data validation occurs before persisting it, to make sure it follows the correct format.

Validation is a cross-cutting task, so we should try to keep it apart from our business logic. That’s why JSR303 and JSR349 provide a specification for validating a bean by using annotations. Hibernate Validator provides the reference implementation of both these bean validation specs. Read more at Hibernate Validation Example.

  1. What is the benefit of Hibernate Tools Eclipse plugin?
    Answer: Hibernate Tools plugin helps us in writing hibernate configuration and mapping files easily. The major benefit is the content assist to help us with properties or xml tags to use. It also validates them against the Hibernate DTD files, so we know any mistakes beforehand. Learn how to install and use at Hibernate Tools Eclipse Plugin.

That’s all for Hibernate Interview Questions and Answers, I hope it will help you in an interview as a fresher or experienced person. Please let me know if I have missed any important question here, I will add that to the list.

  1. How to make an immutable class in hibernate?
    Answer: If you mark a class as mutable=”false”, the class will be treated as an immutable class. By default, it is mutable=”true”.
  2. What is automatic dirty checking in hibernate?
    Answer:
    The automatic dirty checking feature of Hibernate, calls update statement automatically on the objects that are modified in a transaction.

Let’s understand it by the example given below:

  • SessionFactory factory = cfg.buildSessionFactory();
  • Session session1 = factory.openSession();
  • Transaction tx=session2.beginTransaction();
  • Employee e1 = (Employee) session1.get(Employee.class,
  • Integer.valueOf(101));
  • e1.setSalary(70000);
  • tx.commit();
  • session1.close();

Here, after getting employee instance e1 and we are changing the state of e1.
After changing the state, we are committing the transaction. In such a case, the state will be updated automatically. This is known as dirty checking in hibernate.

  1. What is lazy loading in hibernate?
    Answer:
    Lazy loading in hibernate improves performance. It loads the child objects on demand.

Since Hibernate 3, lazy loading is enabled by default, and you don’t need to do lazy=”true”. It means not to load the child objects when the parent is loaded

  1. What is a Session in hibernate?
    Answer:
    A Session is something which is used to get a somatic connection with a database. The Session object is lightweight and is planned to be instantiated each time an interaction is needed with the database.
  2. What is Transaction in hibernate?
    Answer:
    A Transaction signifies a unit of work with the database and maximum of the RDBMS back up the transaction functionalities. Transactions in Hibernate are controlled by a basic operation manager and transaction.
  1. What are the different levels of ORM quality?
    Answer:

Four levels defined for ORM quality:

  • Pure relational
  • Light object mapping
  • Medium object mapping
  • Full object mapping
  • Read: Java.net Connectexception connection refused
  1. What is called lazy fetching from Hibernate?
    Answer:
    In Hibernate Lazy fetching is concomitant with child objects that are loading for their parent objects. By way of a Hibernate mapping file (.hbm.xml), you can specify the selection of loading the various child objects. By default, Hibernate does not load child objects. Lazy=true command means not to load the child objects.
  2. Why do you need ORM tools like hibernate?
    Answer:
    The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides the following benefits:
  • Improved productivity
  • High-level object-oriented API
  • Less Java code to write
  • No SQL to write
  • Improved performance
  • Sophisticated caching
  • Lazy loading
  • Eager loading
  • Improved maintainability
  • A lot less code to write
  • Improved portability
  • ORM framework generates database-specific SQL for you
  1. What Does Hibernate Simplify?
    Answer: Hibernate simplifies:

Saving and retrieving your domain objects
Making database column and table name changes
Centralizing pre-save and post retrieve logic
Complex joins for retrieving related items
Schema creation from the object model

  1. What is the Java Persistence API (JPA)?
    Answer:
    Java Persistence API (JPA) provides a specification for managing the relational data in applications. Current JPA version 2.1 was started on July 2011 as JSR 338. JPA 2.1 was approved as final on 22 May 2013.

JPA specifications are defined with annotations in javax.persistence package. Using JPA annotation helps us in writing implementation independent code

  1. What is Hibernate SessionFactory and how to configure it?
    Answer:
    SessionFactory is the factory class used to get the Session objects. SessionFactory is responsible to read the hibernate configuration parameters and connect to the database and provide Session objects. Usually, an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.

The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping. (framework)

SessionFactory also provides methods to get the Class metadata and Statistics instance to get the stats of query executions, second-level cache details, etc.

  1. What is the difference between open Session and get Current Session?
    Answer:
    Hibernate SessionFactory get current session() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file. Since this session object belongs to the hibernate context, we don’t need to close it. Once the session factory is closed, this session object gets closed.

Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in a multi-threaded environment.

There is another method openStatelessSession() that returns stateless session, for more details with examples please read Hibernate openSession vs getCurrentSession.

  1. What are the important benefits of using Hibernate Framework?
    Answer:
    Some of the important benefits of using hibernate framework are:

Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism, and association.
Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because the learning curve is small and there are tons of online documentation and help is easily available in forums.
Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications.
Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it’s required.
Hibernate cache helps us in getting better performance.
For database vendor-specific feature, hibernate is suitable because we can also execute native sql queries.
Overall hibernate is the best choice in the current market for ORM tool, it contains all the features that you will ever need in an ORM tool.

  1. Name some important interfaces of Hibernate framework?
    Answer:

Some of the important interfaces of Hibernate framework are:

SessionFactory (org.hibernate.SessionFactory): SessionFactory is an immutable thread-safe cache of compiled mappings for a single database. We need to initialize SessionFactory once and then we can cache and reuse it. SessionFactory instance is used to get the Session objects for database operations.
Session (org.hibernate.Session): Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps JDBC java.sql.Connection and works as a factory for org.hibernate.Transaction. We should open session only when it’s required and close it as soon as we are done using it. The session object is the interface between java application code and hibernate framework and provide methods for CRUD operations.
Transaction (org.hibernate.Transaction): Transaction is a single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC or JTA transaction. An org.hibernate.A session might span multiple org.hibernate.Transaction in some cases

  1. Hibernate SessionFactory is thread-safe?
    Answer: the
    Internal state of SessionFactory is immutable, so it’s thread-safe. Multiple threads can access it simultaneously to get Session instances.

41. What is the difference between Hibernate Session get() and load() method?
Answer:
Hibernate session comes with different methods to load data from the database. get and load is the most used methods, at first look, they seem similar but there are some differences between them.

get() loads the data as soon as it’s called whereas loading () returns a proxy object and loads data only when it’s actually required, so load() is better because it supports lazy loading.
Since load() throws an exception when data is not found, we should use it only when we know data exists.
We should use get() when we want to make sure data exists in the database.
For clarification regarding the differences, please read Hibernate get vs load.

42. What is the difference between sorted collection and ordered collection, which one is better?
Answer:
When we use Collection API sorting algorithms to sort a collection, it’s called sorted list. For small collections, it’s not much of an overhead but for larger collections it can lead to slow performance and OutOfMemory errors. Also, the entity beans should implement Comparable or Comparator interface for it to work, read more at java object list sorting.

If we are using the Hibernate framework to load collection data from the database, we can use its Criteria API to use “order by” clause to get ordered list. Below code, snippet shows you how to get it.

43. Why we should not make Entity Class final?
Answer:
Hibernate use proxy classes for lazy loading of data, only when it’s needed. This is done by extending the entity bean, if the entity bean will be final then lazy loading will not be possible, hence low performance.

44. What is HQL and what are its benefits?
Answer:
Hibernate Framework comes with a powerful object-oriented query language – Hibernate Query Language (HQL). It’s very similar to SQL except that we use Objects instead of table names, that makes it more close to object-oriented programming.

Hibernate query language is case-insensitive except for java class and variable names. So SeLeCT is the same as SELECT, but com.journaldev.model.The employee is not the same as com.journaldev.model.EMPLOYEE.

The HQL queries are cached but we should avoid it as much as possible, otherwise, we will have to take care of associations. However, it’s a better choice than a native sql query because of the Object-Oriented approach. Read more at HQL Example.

45. Can we execute native sql query in hibernate?
Answer:
Hibernate provides the option to execute native SQL queries through the use of the SQLQuery object.

For normal scenarios, it is however not the recommended approach because we loose benefits related to hibernate association and hibernate first-level caching. Read more at Hibernate Native SQL Query Example.

46. What is Hibernate Proxy and how it helps in lazy loading?
Answer:
Hibernate uses a proxy object to support lazy loading. Basically when you load data from tables, hibernate doesn’t load all the mapped objects. As soon as you reference a child or lookup object via getter methods, if the linked entity is not in the session cache, then the proxy code will go to the database and load the linked object. It uses javassist to effectively and dynamically generate sub-classed implementations of your entity objects.

47. How to use application server JNDI DataSource with Hibernate framework?
Answer:
For web applications, it’s always best to allow the servlet container to manage the connection pool. That’s why we define JNDI resource for DataSource and we can use it in the web application. It’s very easy to use in Hibernate, all we need is to remove all the database-specific properties and use below property to provide the JNDI DataSource name.

48. How to integrate Hibernate with Servlet or Struts2 web applications?
Answer:
Hibernate integration with Servlet or Struts2 needs to be done using ServletContextListener, a complete example can be found at Hibernate Struts2 Integration Example.

49. Which design patterns are used in Hibernate framework?
Answer:
Some of the design patterns used in Hibernate Framework are:

Domain Model Pattern – An object model of the domain that incorporates both behavior and data.
Data Mapper – A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself.
Proxy Pattern for lazy loading
Factory pattern in SessionFactory

50. What are the inheritance mapping strategies?
Answer:
There are 3 ways of inheritance mapping in hibernate.

1. Table per hierarchy
2. Table per concrete class
3. Table per subclass

Note: Browse latest  hibernate interview questions and Hibernate tutorial. Here you can check  Hibernate Training details and Hibernate training videos for self learning. Contact +91 988 502 2027 for more information.

Leave a Comment

FLAT 30% OFF

Coupon Code - GET30
SHOP NOW
* Terms & Conditions Apply
close-link