Top 50 Hibernate Interview Questions | Spring Interview Questions – SVR 24/7

Top 50 hibernate interview questions

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 java based ORM tool that provides framework for mapping application domain objects to the relational database tables and vice versa.  ( Top 50 Hibernate Interview Questions)

Hibernate provides reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use Hibernate persistence API for CRUD operations. Hibernate framework provide 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 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 java application layer and hibernate. This is the core interface used to perform database operations. Lifecycle of a session is bound by the beginning and end of a transaction.
Session provide 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 thread safe, every thread should get it’s 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?

Hibernate uses Reflection API to create instance of Entity beans, usually when you call get() or load() methods. 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 native sql query and use join keyword.

7.What is 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 getCurrentSession() method to get the current session and use it to get the spring transaction management benefits. If you go through above examples, you will see how easy it is and that’s why we should not use these classes anymore. (Top 50 Hibernate Interview Questions)

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 toget() strategy if you don’t know about 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 make 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 actully called on the Parent object.But in some cases you do need to load the child objects when parent is loaded.
Just make the lazy=false and hibernate will load the child when parent is loaded from the database.

12.Explain the mechanism by which you can distinguish between transient (i.e. newly instantiated) and etached 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 of hibernate 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 save programmers time to write the SQL code as there is no need to write the SQL code in it. These tools provide 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 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 (Top 50 Hibernate Interview Questions)

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 allow the storing of 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 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 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 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 use of Hibernate Session merge() call?

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

19. What is difference between Hibernate Session get () and load () method?

Answer: Hibernate session comes with different methods to load data from database. get and load are most used methods, at first look they seems similar but there are some differences between them.

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

(Spring Interview Questions)

Since load() throws 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.

(Top 50 Hibernate Interview Questions)

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

21. 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.
A good relationship management and offers code for mapping an object right to the data.

22. 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 with 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. (java training)
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 is 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.

23. What are 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 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 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 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 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

24. What is Hibernate Validator Framework?

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

Validation is a cross cutting task, so we should try to keep it apart from our business logic. That’s why JSR303 and JSR349 provides 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.

25.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 before hand. 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 for 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.

26.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”.

27. 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:
1. …
2. SessionFactory factory = cfg.buildSessionFactory();
3. Session session1 = factory.openSession();
4. Transaction tx=session2.beginTransaction();
5.
6. Employee e1 = (Employee) session1.get(Employee.class, Integer.valueOf(101));
7.
8. e1.setSalary(70000);
9.
10. tx.commit();
11. 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.

28. What is lazy loading in hibernate?

Answer: Lazy loading in hibernate improves the 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

29.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.

30. 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.

31. What are the different levels of ORM quality?

Answer: Four levels defined for ORM quality:

Hibernate Interview Questions & Answers

Pure relational
Light object mapping
Medium object mapping
Full object mapping
Read: Java.net Connectexception connection refused

(Top 50 Hibernate Interview Questions)

32. 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.

33.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 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

34. 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 object model

35. What is Java Persistence API (JPA)?

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

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

36. 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 provide methods to get the Class metadata and Statistics instance to get the stats of query executions, second level cache details etc.

37. What is difference between open Session and get Current Session?

Answer: Hibernate SessionFactory getCurrentSession() 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 multi-threaded environment.

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

38.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 learning curve is small and there are tons of online documentations 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 current market for ORM tool, it contains all the features that you will ever need in an ORM tool.

39. Name some important interfaces of Hibernate framework?

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. Session object is the interface between java application code and hibernate framework and provide methods for CRUD operations. (Spring Hibernate Training Videos)
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. A org.hibernate.Session might span multiple org.hibernate.Transaction in some cases

40. Hibernate SessionFactory is thread safe?

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

(Top 50 Hibernate Interview Questions)

41. What is difference between Hibernate Session get() and load() method?

Answer: Hibernate session comes with different methods to load data from database. get and load are most used methods, at first look they seems similar but there are some differences between them.

get() loads the data as soon as it’s called whereas load() returns a proxy object and loads data only when it’s actually required, so load() is better because it support lazy loading. (spring hibernate training online)
Since load() throws 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 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 Hibernate framework to load collection data from database, we can use it’s 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 it’s 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 is the same as SELECT, but com.journaldev.model.Employee is not 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 native sql query because of Object-Oriented approach. Read more at HQL Example.

45. Can we execute native sql query in hibernate?

Answer: Hibernate provide option to execute native SQL queries through the use of 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 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 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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Training Features

*  Online  and Self-Paced Training
*  Fast-track / Regular / Weekend
*  Free Videos Access
*  Flexible Timings
*  Lowest Fee
*  Friendly Support


 
Talk To Faculty
ENQUIRE NOW
close-link