Hibernate Interview Questions in 2021
1. What is Hibernate?
Ans:- Hibernate is an object-relational mapping tool which is going simplifies the java application interaction with the Database. It provides the facility to map the java classes to relational database tables and Java data types to SQL data types. which means using hibernate we can simplify the java development effort to talk to the database. It is an open-source persistent framework started by Gavin King in 2001.
2. What is ORM tool?
Ans:- ORM stands for object-relational mapping is a programming technique for converting data between a relational database and an object-oriented programming language such as java, c#, etc.
Advantage of ORM tool over JDBC.
1.it hides the SQL queries from object-oriented logic
2.fast development of application
3.transaction management and automatic key generation.
4.no need to deal with the database implementation.
3. What is the core interfaces of hibernate?
Ans:-the five core interfaces are used in just about every Hibernate application. using these interfaces you can store retrieve persistent objects and control transaction.
1-Session interface -this is the primary interface used by hibernate applications. The instance of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread-safe.
2-SessionFactory interface-this is a factory that delivers the session objects to hibernate application. Generally, there will be a single SessionFactory for the whole application and it will be shared among the application threads.
3-Configuration interface-this interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.
4-Transaction interface-this is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementation such as JDBC transaction.
5-Query and criteria interface -this interface allows the user to perform queries and also control the flow of the query execution.
4. Mention some of the advantages of using ORM over JDBC?
Ans:- 1.it hides the SQL queries from object-oriented logic
2.fast development of application
3.transaction management and automatic key generation.
4.no need to deal with the database implementation.
5.no need to deal with the SQL Queries to save and retrieve the data.
6.easy to learn and use.
7.excellent cashing support for the better performance of the application.
5. Explain hibernate architecture?
Ans:- Java application gives the persistence to hibernate framework in the form of object that it has interacted with the particular database software and hibernate framework uses hibernate configuration file info to locate the destination database software and to interact with the database software by using appropriate JDBC driver that means in this file mainly information will available to locate and interact with that certain database software using certain JDBC driver after interacting to database software how does hibernate knows? It has to generate SQL query with respect to which table it has to perform persistence operation with respect to which table and which column that information it will gather what hibernate mapping file this is the file where class will be mapped with which class domain class will be mapped with what table and domain class properties that means java class member variable beam properties will be mapped with what DB table column if necessary it also configure one or other property as what identifier property and that will be utilized to perform synchronization so as part of synchronization that property value will be to list as what criteria value what do mean by synchronization any modification than object of java application reflect to table row any modification done in table row will reflect what object and that will happen by using one or other select query or update query for those query some identifier value is required as what criteria value so which property value of domain class object should be taken as what identity value should be taken as criteria value will also be configured through what mapping file.
What is the use of domain class -if this domain class is not there, there is no possibility of creating objects representing table boss so, hibernate is known for developing what objects based persistence logic to create those objects when our other classes required that class is called domain class generally it is java bean, generally it is a POJO class. Using this domain class only will develop object-based persistence logic so this because domain class representing table rows will maintain synchronization between objects and table rows.
Hibernate can take the support of JTA for that kind of transaction management.
Hibernate uses JDBC to develop SQL queries based a persistence logic to interact with the database software for a connection pool-related activities it takes the support of JTA for transaction management related activities it sorts take the support of JTA.
6. Define criteria in terms of hibernate?
Ans:- The hibernate Session interface provides createCriteria() method, which can be used to create a criteria object that returns instances of the persistence object’s class when your application executes a criteria query.
Example of criteria:-
Criteria cr = session.createCriteria(GreatLearning.class);
List results = cr.list();
7. List some of the database supported by hibernate?
Ans:- Given below is the list of most popular database management systems-
- SolarWinds Database Performance Analyzer
- Oracle RDBMS
- IBM DB2
- Microsoft SQL Server
- SAP Sybase ASE
- Microsoft Access
8. Mention two components of Hibernate configuration object?
Ans:- It is usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate.
The Configuration object provides two keys components –
DATABASE CONNECTION-This is handled through one or more configuration files supported by Hibernate. These files are hibernate. Properties and hibernate.cfg.xml.
CLASS MAPPING SETUP − This component creates the connection between the Java classes and database tables.
9. List the key components of Hibernate?
10. How is SQL query is created in hibernate?
Ans:-The entity manager interface provides a method called create native career avoid this method returns an implementation of equilibria interface which is same as if you call the create query method to create equity the code to a JPA.
Call EntityManager.createNativeQuery(String query)method.
Query q=em.createNativeQuery(“SELECT a.firstname,a.lastname”+”FROM Author a”);
Create hibernate.cfg.xml configuration file
Create Employee.hbm.xml mapping file
Create Employee.java source file and compile it.
Create ManageEmployee.java source file and compile it.
Execute ManageEmployee binary to run the program.
11. What does HQL b for?
Ans:- HQL stands for hibernate query language.
12. How to enable hibernate in windows 10?
Ans:-To enable hibernate in windows 10, click on window(symbol)+R, then you see bottom of the window in that type power options or if u say like Cortana, just say “Hey Cortana launch power options”.another way to get the power option in the control panel. From the left column, select choose what the power buttons do
Next, if options are greyed out, select change settings that are currently unavailable. Scroll down and check to hibernate box, after that make sure save your settings.
Now, when you open the start menu and select the power button the hibernate option will be available. Then click on Alt+f4 then following the steps above adds the hibernate mode option as well.
13. What is the dialect in hibernate?
Ans:- For connecting hibernate application with database then we must specify the SQLDialect, which contain the mapping between java language data type and database datatypes. There are many dialect classes for defining the RDBMS.
Hibernate uses dialect configuration to know which database you are using so that, it can switch to the database-specific SQL generator. Hibernate generates all your entity mappings and hibernate queries to Specific database query and uses JDBC to execute them.
14. What is n+1 problem in hibethorugh rnate?
Ans:- I want to tell one problem regarding n+1 in hibernate to understand this solution.
Let us assume you have a number of employees in a company and every employee have some number of projects. So, one to many relations between employee and projects. now you have to iterate through the collection of employee and display all the projects name they have .so the Query will look like this below,
SELECT * FROM employee
SELECT * FROM projects WHERE employeeId=?
Here you have 1 select statement for the employee and if you have n number employee you have to write one more query to select the projects. So at the last, you have to put n+1 select statement in order to perform this operation.
Now the next question is how to solve it?
Using join fetching(it will join the parent and children and fetch all the information in a single statement) we can able to solve the n+1 problem.
Now our next query will look like this,
“FROM employee e JOIN FETCH e.projects p”
15. How to enable second-level cache in hibernate?
Ans:- To enable second-level cache we need to follow some points regarding cache, First level cache enabled by default. Whenever we are loading any object from the database, Then hibernate verify whether that object is available in the local cache memory of that particular session, means first level cache, if not available then hibernate verify whether the object is available in global cache or factory cache second-level cache, if not available then hibernate will hit the database and loads the object from there, and then first stores in the local cache of the session, the first level then in the global cache second-level cache.
16. What is cascade in hibernate?
Ans:- Cascading is about persistence actions involving one object propagating to other objects via an association. Cascading can apply to a variety of Hibernate actions, and it is typically transitive. The cascade attribute of the annotation that defines the association says what actions should cascade for that association.
Cascade = “all” means to apply all primary cascade types. As of Hibernate 5.3, these types are:
1.delete / remove
17. What is a session in hibernate?
Ans:- Session is a lightweight object. The session provides physical connectivity between java application and database. the Session will be established each time java application wants to do something with the database. Session object will be provided by the SessionFactory object. All the persistent objects will be saved and retrieved through the Session object. The session object must be destroyed after using it.
The session is used to create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states:
18. How to integrate spring with hibernate?
Ans:- Integrate spring with hibernate using Maven
1-no need to define hibernate.cfg.xml
2-we provide all our configuration in the spring config file.
Steps to integrating-
1.Configuration cfg=new configuration();
Steps to create a simple spring ORM application;
– create table
– spring configuration file
– model class
– dao class
– test class
19. What is the sessionFactory in hibernate?
Ans:- sessionFactory is an interface, which contains session instance from a sessionFactory.there is a single sessionFactory for the whole application created during application initialization.
The sessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and maybe reused in a future unit of work.
20. How is HQL query created?
Ans:- HQL stands for hibernate query language, HQL is an object-oriented language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties
HQL queries are translated by Hibernate into conventional SQL queries.
21. Is SessionFactory a thread-safe object?
Ans:- Yes, SessionFactory is a thread-safe object, many threads can access simultaneously.
22. What is Session?
Ans:-Session simply means a particular interval of time.
It maintains the connection between the hibernate and database, which is available in the org.hibernate.Session interface which provides methods to insert, update and delete the object.
23. Is Session a thread-safe object?
Ans:-No, the session is not a thread-safe object, many threads cant access it simultaneously. In other words, you cannot share it between threads.
24. What is the difference between the session.save() and session.persist() method?
Ans:- The return type of the Session.save() method is java.io.Serializable.It returns the newly generated identifier id value as a serializable object. While return type of the session.persist()method does not return anything.
25. What is the diff between update and merge method?
Ans:- Merge is like combining records from more than one table (while retrieving records from tables based on some conditions)
The update is like edit, use to change the value of the record.
If you are sure that the session does not contain an already persistent instance with the same identifier, then use the update to save the data in hibernate
If you want to save your modifications at any time without knowing about the state of a session, then use merge() in hibernate.
SessionFactory factory = cfg.buildSessionFactory();
Session session1 = factory.openSession;
Employee e1 = null;
Object o = session1.get(Employee.class, new Integer(101));
s1 = (Employee)o;
Session session2 = factory.openSession();
Employee s2 = null;
Object o1 = session2.get(Employee.class, new Integer(101));
s2 = (Employee)o1;
26. What is automatic dirty checking in hibernate?
Ans:- The automatic dirty checking feature of hibernate, calls update statement automatically on the object that is modified in a transaction.
Let us understand it by the ex:-
Here, after getting employee instance e and we are changing the state of e
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.
27. What is diff b/w first level cache and second level cache?
First level cache:-
the first level cache is the session cache.it is mandatory cache through which all requests must pass. The first-level cache in hibernate is enabled by default. we cannot disable the first level.
First level cache is associated with the Session object. The session object is created from SessionFactory and it is close lost, once the session is closed.it is retrieved from the database and stored in a first-level cache associated with hibernate session.
This is an optional Cache which Hibernate provides. Unlike first level cache which is accessible only to the session who maintains it, Second-level Cache is accessible to all Sessions.
The Second Level cache is by default disabled. Hibernate also doesn’t provide any caching implementation for that.
28. What is a transaction in hibernate?
Ans:- a transaction represents a unit of work. If u want the database to do some work for u. then u need to start a transaction and let the database know you are done.
Your transaction will commit when you call session.flush().
29. How to create hibernate projects in eclipse?
Ans:- steps to create hibernate projects in eclipse
- First, create the java project in eclipse
- Download the hibernate from a website then it shows to your download hibernate library then hit into the hibernate after download, add jar files to hibernate.
- Add MySQL JDBC driver to file
- Then, Create a Persistent class with mapping information
- After creating persistence class then again create the Hibernate Configuration file
- Create a Utility class for initializing the SessionFactory
- Create Example code to load the data from Database
- After doing all the above points right-click on mouse u see run option then hit on the RUN
- Run the Example.
30. How to retrieve data from database using hibernate and spring
Ans:- To retrieve data from the database, you simply leverage the Hibernate sessions createQuery method, pass in some HQL, convert the guts of the returned Query object into an easy to use List, and then loop through the collection of your POJOs contained in the List.