Hibernate is a popular ORM tool that is used in enterprise applications for database related operations and other java applications. Therefore, top companies are looking for hibernate experts for their day-to-day operations. So, I have decided to write an article on the hibernate interview questions and answers which is mandatory to polish your knowledge before the interview.
Hibernate has significant importance in the java world because it frees the java developers from writing complex JDBC code converting SQL columns into object properties. It also offers out-of-box solutions on proxying, caching, and lazy loading which improves the overall performance of java web applications. So, the spring and hibernate interview questions are mostly asked in java interviews for web development positions.
Hibernate is written in java and it is based on JVM (Java Virtual Machine). It is an open-source software which is used for mapping java classes to data tables and java data types to SQL data types. Hibernate makes it easier to create objects independent of database software and provides a reference implementation of java persistence API that is used for CRUD operations.
Object Relational Mapping (ORM) is a programming technique that is used to convert data between relational databases and OOP (Object Oriented Programming) languages such as C#, Java, etc.
Java Persistence API (also known as JPA) has the specification for managing the relational data in several applications. JPA’s current version 2.1 was started in July 2011 but approved as final on 22 May 2013. It also helps us in writing implementation-independent code.
Hibernate is an ORM tool that is used to save the state of any java object into the database whereas JPA defines the management of relational data in the java applications.
Hibernate architecture is based on many objects including session factory, persistent object, connection factory, transaction, session, transaction factory, etc. It is categorized into the following layers:
As you can view in the diagram given below:
Hibernate Query Language (HQL) is an object-oriented language that is independent of the database and considers the java objects in a similar way as that of the SQL.
The HQL query is created with the following syntax:
The flow of hibernate communication with RDBMS is:
Hibernate validator framework allows to express and validate different constraints of the application by overriding and extending through XML. Moreover, it is available for both server and client-side programming.
Following are the main benefits of using the Hibernate Framework:
Following are the key advantages of the hibernate framework over JDBC:
Following design patterns are used in the Hibernate framework:
Following are the hibernate supported databases:
Following best practices are recommended when we use the hibernate:
Hibernate can be configured in the following ways:
In the configuration, the dialect knows which database you are using so that it can be switched to the database specific SQL generator code whenever you needed.
Hibernate is one of the popular ORM frameworks and spring is a widely used java EE framework. So, the spring hibernate combination is used in a lot of enterprise-level applications. Following are the simple steps for hibernate and spring integration:
The mapping file is one of the key features of hibernate because it is a compulsory feature for every ORM tool. In fact, it is a mechanism of placing an object property into columns of a table because it establishes a relationship between two database tables as attribute in their model and allows you to easily navigate the criteria queries and associations in your model.
The SQL query is created using the following syntax:
We can get the hibernate statistics by setting the property hibernate.generate_statistics to true. It will show a number of useful metrics but it is only available in development mode.
Class Mapping Setup
Following are the simple steps to map an entity to 2 database tables:
Following are the requirements for an entity class:
Bag is a java collection which is used to store the elements without caring about sequencing and allow duplicate elements in the list. In simple words, it is a random grouping of the objects in a list that is mapped with a <bag> element.
As the name indicates sorted collection is based on the elements having order but the order depends on the value of the element such as the sorted set.
An ordered collection is the name of elements having specific order and it is independent of the value such as a list.
Following are the core interfaces of hibernate framework:
Hibernate session is a runtime interface that is used between the application and hibernates. In simple words, it establishes a connection between the application and database in order to perform different functions such as create, delete, get, update.
No, it is not a thread-safe object because it can be accessed by multiple threads.
SessionFactory.openSession creates a new session object and give it to you for performing different operations. But keep in mind, you need to close these session objects because these are not thread safe. If you have multithreaded environment then you need to create one session per request. Moreover, one session per request is also used in web applications.
SessionFactory.getCurrentSession creates a new session if not exists otherwise it will use the same session. The object provided by the getCurrentSession is managed internally and automatically close the session when a transaction ends, so there is no need to manage it externally.
SessionFactory can be created by providing a configuration object and it is a n interface that contains all DB related property details pulled by hibernate.properties or hibernate.cfg.xml. In short, it is a factory for session objects that is created during application start up and kept for later use because it is a heavyweight object.
Yes, many threats cannot access it at the same time.
Eager loading is a design pattern in which the data initialization phase is completed on the spot and it is considered the best option when the relations are not too much. It is the best practice to reduce the further queries on the server.
Lazy loading means whenever the select query is executed it will not directly access the database and wait for the function i.e when we need then it will fetch from the database.
Lazy initialization or lazy fetching is the opposite of eager and it means when a record is loaded for the database the child rows ( in case of one to many relationship) are not loaded.
It is about persistence actions involving an object propagating to other objects with the help of association. Cascading can apply to a range of hibernate actions and it is characteristically transitive.
Merge() is used to synchronize all data changes such as removal and addition of row but update can only modify column values.
Persist() method is similar to save method that is also used to INSERT the records in the database but it has void return type whereas the save has the return type of Serializable Object.
It is a problem that happens when the data access framework executed N additional SQL statements to fetch the same data that could have been accessed when executing primary sql statements/queries. The larger value of N the more queries will be executed and have a great performance impact.
The named query is the name of a predefined unchangeable query string which is similar to alias names. It can be defined by mapping file or annotation.
The main benefit of hibernate criteria API is that it is dedicatedly designed to manipulate data without any hard-coded SQL statements.
The transaction an event that represents a unit of work that can be described by ACID properties (Atomicity, Consistency, Isolation and Durability). So, if one step fails, the whole transaction fails which is known as atomicity.
Transaction propagation shows if any component will or will not participate in any particular transaction and how will it behave if the calling service or component already has or does not have a transaction created already.
Following are the Hibernate isolation levels: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE.
Before committing the transaction, optimistic locking is used when you check if the record was updated by someone else. In case of pessimistic locking, the you take an exclusive lock so that you can make sure no one else can modify the record.
There are two caching levels are existing in the hibernate: first level cache and second level cache. In the first level cache, objects are cached within the current session and only alive until a session is closed but second level cache exists as long as the SessionFactory is alive.
First level cache provides the session level in the process caching. Once the session is created, a session cache is associated with it and the copy of a session cache is maintained when an object is loaded in from the database.
No, you cannot disable the 1st level cache.
2nd level cache is a store of entity data managed by the persistence provider in order to improve the performance of application by avoiding expensive database calls and keeping the entity data local to the application.
The main difference is that 1st level cache is maintained at the session level while the 2nd level cache is maintained at SessionFactory. The data stored in the first level cache is only accessible to the session who maintains it while the second level cache is accessible to all.
You can use the session evict() method in order to remove a single object from the first level cache but if you want to delete all the objects from the cache then session clear() is used for this purpose.
That’s all for Hibernate Interview Questions and Answers, I hope it will help both beginners and experienced person. Moreover, take a look at compulsory things including industry research, reasons you want the job, preparation for common interview questions, practice, practice and practice. Moreover, you can also prepare 100+ SQL Interview Questions and Answers in order to understand the database concepts.