Below are few major features of Hibernate
Q1. What is difference between Getcurrentsession() and Opensession() method in hibernate?
The difference between Getcurrentsession() and Opensession() method in hibernate can be stated as SessionFactory. getCurrentSession() returns a session bound to a context and provides you session object which is in hibernate context and managed by hibernating internally. Whereas openSession() always opens a new session that you have to close once you are done with the operations.
Q2. What is open session in hibernate?
An open session method in hibernate is used to open a new session. We have to close the session object as soon as we are done with all the operations of the database. It is necessary to open a new session for each request in the multi-threaded environment. Sessionfactory.opensession() is used in this regard. We have to explicitly flush and close the unused session objects. We need to create one session object per request in a multithreaded environment and only one session per request in the applications of the web because session objects are not considered to be thread-safe. In hibernation, when an open session is applied, it returns a new session object on every call.
Q3. What is the default fetch type in hibernate?
The default fetch type in the hibernate is the lazy fetching. Hibernate uses lazy select fetching for collections. It also uses the lazy proxy fetching for single-valued associations.
Q4. Explain dirty checking in hibernate?
Hibernation offers a dirty checking facility. It is advantageous to save the time and effort of developers in order to update the database when states of objects are changed or modified inside a transaction. Hibernate recognizes the changes in object states and thereby synchronized with the database for its updating. Here the essential updating and modifications are done without affecting the other fields in the database. We can say it is a method of checking all managed entities (each persistent object of that entity) properties.
Q5. What is Evict in hibernate?
Evict() method in hibernate is used to detach/dissociate the object from its cache session as we need to make changes. Any change to the object will not be persistent, after detaching the object from the session. Suppose we are waiting for getting the input from the user, in this case, we can detach the object instance from the hibernate session and this is done by evict() method. In layman's language, we can say that it removes the specified object from the current session. One should also keep a check that the object is in session before calling the evict(). It occurs outside any transaction and evicts all the entries from the cache.
Q6. What are JPA Annotation?
JPA – Java Persistence API annotations are simplified as an object-relational mapping that allows defining how to map Java objects to relational database tables. They are mapped in a standard and portable way.
With a Java source code, a form of metadata like Java annotation is added. Since Java annotation is added with the source file, it can only be viewed in the source file.
Below are few JPA Annotations used for mapping java objects to the database table.
Q7. How can we invoke stored procedures in hibernate?
There are three ways to call stored procedures in the Hibernate.
In the NativeSQL, you can use createSQLQuery() to call a store procedure directly.
In the NamedNativeQuery, you can declare your store procedure inside the @NamedNativeQueries annotation.
In the SQL-query in the XML mapping file, you can declare your store procedure inside the “SQL-query” tag.
Q8. What is difference between session.get() and session.load() method in hibernate?
The difference between sessions.get() and session.load() method in hibernate can be stated as the Get() method return null, If no row is available in the session cache or the database for the given identifier whereas the Load() method throws object not found exception.
Q9. List few disadvantages of hibernate?
There is a certain disadvantage in the hibernate framework. Some of them we have listed below
Q10. What is a proxy in hibernate?
Proxy is a function that is authorized to act as the deputy or substitute for another. In the Hibernate, the proxies are the classes that are generated dynamically by the Hibernate to help with the lazy loading. If you generate a class, then the Hibernate will generate a proxy class that extends the desired class. This subclass is implemented at the runtime. The proxy is created instead of querying the database directly, and this proxy will load the real object from the database whenever one of its methods is called.
Q11. Explain how Caching works in Hibernate?
Caching is a mechanism that is used to enhance the performance of the system. The cache memory lies between the application and the database and stores recently used data items. It is done to reduce the number of database hits as much as possible.
Hibernate uses multi-level caching such as first-level cache, second-level cache, and query-level cache. The first-level cache is the session cache which is mandatory through which all the requests must pass. The Second-level cache is optional which is consulted after an attempt is made to locate an object in the first-level cache. The query-level cache is implemented to cache for query resultsets. This is closely integrated with the second-level cache.
Q12. What is use of Hibernate QBC API?
Hibernate query by criteria (QBC) API is generally used to generate queries by use of criteria objects at run time. In Hibernate QBC API, you can apply rules like filtration and logical conditions.
Q13. What is Light Object Mapping in Hibernate?
In Light Object Mapping terminology, the mapping is done manually to the relational tables, where the entities are represented as classes. Using different design patterns, the code is hidden from the logic. This terminology is well known because it is used for applications with a smaller number of entities.
Q14. What is ordered collection and sorted collection in Hibernate?
The sorted collection is sorted using the sorting features provided by the Java collections framework. It is done in the memory of JVM that is running in hibernate. This sorting is done soon after reading data from the database using the Java Comparator. In the sorted collection, less the collection, the more efficient it will be the sorting.
The Ordered collection is used to sort the collection by using the order by clause for the results fetched. In the ordered collection, the more the collection, the more efficient will be the sorting.
Q15. What is Hibernate Framework?
Hibernate framework helps and also makes it easy in the development of the Java application. It is basically an object-relational mapping tool that also can be said those tools with object-oriented programming.
Below are the certain advantages of using this framework:
Q16. What is Java Persistence API (JPA)?
The Java Persistence API (JPA) is the specification of Java that is used to persist the data between the Java object and the relational database. So it essentially acts as a bridge between the object-oriented domain models and the relational database systems. The JPA is just a specification so it doesn’t perform any operation by itself. But the JPA specifications are implemented by ORM tools like the Hibernate, TopLink, and iBatis.
Q17. What are the important benefits of using Hibernate Framework?
The important benefits of using Hibernate Framework are:
Q18. Name some important interfaces of Hibernate framework?
Some important interfaces of Hibernate framework are:
Q19. What is hibernate configuration file?
The Hibernate configuration file has configuration parameters such as the mapping information that provides different functionalities to the Java class. This database-related mapping information is usually found in the configuration file. It is an XML file like hibernate.cfg.xml.
Q20. What is hibernate mapping file?
The Hibernate mapping file is used by the Hibernate framework to get the information regarding the mapping of the POJO class and the database table. The mapping information found in the hibernate mapping file is the mapping information of a POJO class name to the database table name and the mapping information of POJO class properties to the database table columns.
Q21. What is Hibernate SessionFactory and how to configure it?
Hibernate SessionFactory is an object created by the configuration object. It is a heavyweight object that contains all the configuration properties related to the database. A single SessionFactory object is created for every database in the application.
It is created when the application starts and is kept for later use. It is used by all the threads in the application as it is a thread-safe object.
Q22. What is Hibernate Session and how to get it?
Q23. What is the difference between Hibernate Session get() and load() method?
Q24. What is hibernate caching? Explain Hibernate first level cache?
When we need to reduce the database queries, we take the advantage of using Cache. So automatically the throughput time of the application will be reduced. So hibernate cache is used for fast application performance.
There is a direct link with the session object and Hibernate first level cache. When the program runs, hibernate first level cache enables automatically and the option for disabling the cache is minimal. Either the object can be deleted or clear the cache thoroughly.
When a session is closed, all the caches will be closed automatically.
Q25. What is difference between Hibernate save(), saveOrUpdate() and persist() methods?
The save() and saveorupdate() method is used to move the object form transient state to persistent state but there is a significant difference between them.
The save() method creates a new identifier for the object and inserts it into the database.
The saveorupdate() method does either insert or update operations based upon the existence of the object. Also, save() method brings only the transient state object to the persistent state whereas saveorupdate() methods bring both the transient and detached state object into the persistent state.
Q26. What is the difference between sorted collection and ordered collection, which one is better?
Q27. What are the collection types in Hibernate?
The different collection types in the Hibernate are the ArrayType, BagType, CustomCollecctionType, IdentifierBagType, ListType, MapType, and the SetType.
Q28. What is HQL and what are it benefits?
HQL – Hibernate query language is hibernate's own language which is used to activate bulk operations in hibernate programs.
Below are the benefits of using HQL commands.
Q29. What is Query Cache in Hibernate?
The Query Cache in the Hibernate is used for caching the results of the queries. It is done so that the traffic between the application and the database can be reduced by storing the frequently accessed query results in the query cache. Query Cache is one of the three levels of caching, the other two being the first-level cache and the second-level cache.
Q30. What is Named SQL Query?
The Hibernate Named query is used to query the database by some meaningful name. This gives the query an alias name so the application programmer needs not to scatter queries to all the java code.
Two ways of defining a named query in Hibernate is by annotation and by mapping file.
Q31. How to log hibernate generated SQL queries in log files?
Q32. What is Hibernate Proxy and how it helps in lazy loading?
For every entity, a proxy gets generated by the hibernate.
Proxy is generally generated during runtime and lazy loading is one of its behavior. To make it simple, let us talk about parent object and child object. When the parent object is under loading, the hibernate proxy decides to load the child object slow. Slow in loading is termed as lazy loading and it helps to keep the parent object as fast as possible.
Q33. How to implement relationships in hibernate?
Q34. What is cascading and what are different types of cascading?
Q35. What is HibernateTemplate class?
HibernateTemplate class is a helper class in Hibernate that is used to simplify the data access code. This class supports automatic conversion of HibernateExceptions checked exception into DataAccessExceptions which is an unchecked exception. Hibernate template classes are mainly used in business logic services.
Below are a few benefits of Hibernate template class.
Q36. How to integrate Hibernate with Servlet or Struts2 web applications?
Q37. Which design patterns are used in Hibernate framework?
Q38. What is Hibernate Validator Framework?
The Hibernate Validator framework allows you to express and validate the application constraints. It is not tied to a specific application tier or programming model, but it is available for both the server and client application programming. You need to add the Hibernate-validator dependency in order to use the hibernate validator with the maven project. It also requires the implementation of the Unified Expression Language for evaluating the dynamic expressions in the constraint violation messages.
Q39. What is the benefit of Hibernate Tools Eclipse plugin?
Q40. What is Hibernate? Explain with few advantages?
Hibernate is an open-source Java framework for mapping java objects with a database. It is an Object Relational Mapping tool that implements the Java Persistence API for creating persistence with the database. It is a lightweight and high-performance framework that is used to map Java classes and types to database tables and SQL data types.
It also gives the developer the tool to perform data queries and retrieving options with the database. The Hibernate open-source framework is licensed under the GNU LGPL (Lesser General Public License).
Q41. What is difference between Lazy Vs Eager fetching?
Q42. What is automatic dirty checking?
The dirty checking in the hibernate is used to automatically detect whether an object is modified or not and needs to be updated. With the dirty checking, all the necessary updating and changes are done without affecting other fields. It automatically detects the object states whenever changes and updates the database thereby saving the developers time.
Q43. For what Hibernate.cfg.xml file is used?
Q44. What is Session Factory?
Q45. What are various States of hibernate object?
In hibernate, an object will belong in any of the following three states,
Q46. What is the difference between the first and second level caches in Hibernate?
Q47. What is difference between update vs merge in Hibernate?
Q48. What is ORM? List the ORM levels available in Hibernate?
ORM (Object Relational Mapping) is used for converting data between the incompatible type systems. It uses an object-oriented language for converting the data.
The four levels of the ORM in Hibernate are,
Pure Relational ORM - In this level, the entire application is designed around the relational model.
Light Object Mapping - In this level, the entity classes are mapped manually to the relational tables. Applications that have less number of entities use this level.
Medium Object Mapping - In this level, the application is designed around an object model. Here, the associations between the objects are supported by the persistence mechanism.
Full Object Mapping - It is one of the most sophisticated objects modeling level. This level supports composition, inheritance, polymorphism, and persistence.
Q49. List few core interfaces of the Hibernate framework?
Q50. List the Collection types available in Hibernate ?
Q51. What are the Transaction Isolation Levels?
Transaction isolation determines the visibility of changes made by one transaction for another transaction without any interference with the user data. This process is done consistently without any skip in the process. For a high level of isolation, the database fixes lock on data.
Below are few isolation levels that are commonly used.
Q52. How do you create a session object in Hibernate?
Q53. List some common JPA annotations used in Hibernate?
Q54. What is difference between Get vs Load in Hibernate?
Q55. Explain how Save is different from Persist?
Q56. What is HQL?
HQL (Hibernate Query Language) is an object-oriented querying language used in the Hibernate framework.
Q57. List the query types available in hibernate?
Q58. Define cascade and inverse option in one-many mapping?
Q59. What interface lets you write HQL?
Q60. Which annotation is used for sequences in Hibernate?
Q61. Bootstrapping in Hibernate is performed by which core interface?
Q62. How to create a transaction object in Hibernate?
Q63. What is a Named SQL Query?
Q64. Explain the differences between sorted and ordered collection in hibernate?
Q65. What are the ways to express joins in HQL?
Q66. What is Hibernate proxy?
Q67. List few advantages of Hibernate over jdbc?
Below are a few advantages of hibernate over JDBC.
Q68. What is JPQL?
The Java Persistence Query Language (JPQL) is an object-oriented query language. It is defined as a part of the Java Persistence API (JPA) specification. This language is used to create queries against entities to store in a relational database. Based on the SQL syntax, JPQL uses SELECT, UPDATE, DELETE clause to perform database related operations.
Q69. What is difference between openSession and getCurrentSession?
Q70. For what saveOrUpdate() method is used in hibernate?
The saveOrUpdate() method is used to do either INSERT or UPDATE SQL query depending upon the object’s existence in the database. It first uses the SELECT query to determine if it needs to do INSERT or UPDATE operation. The saveOrUpdate method is also used to bring both the transient and the detached object into the persistent state.
Q71. List few Differences between session vs session factory in Hibernate?
The difference between session and session factory in Hibernate can be stated as SessionFactory objects are one per application and Session objects are one per client. SessionFactory is to create and manage Sessions. Whereas Session is to provide a CRUD interface for mapped classes, and also access to the more versatile Criteria API.
Q72. How to run hibernate update query?
In order to run hibernate update query you can use the following given steps:
Q73. What is flush in hibernate?
The flush method in hibernate is used to force the session to flush. It synchronizes the session data with the database. By default, the hibernate will automatically flush changes for you before some query execution and when a transaction is committed.
Q74. Enlist major features of Hibernate?
Some of the Major Features in Hibernate Are:-
Q75. Enlist core components of Hibernate?
The core components in the Hibernate architecture are,
Configuration Object – It has the configuration properties of the Hibernate. It is created first when creating the hibernate application. It has two components, Database connection, and class mapping setup. The Database connection provides the configuration for the connection. The class mapping creates the connection between the java class and the database.
SessionFactory Object – It is used to configure the Hibernate application. It is instantiated by the Configuration Object for every database using a separate configuration file.
Session Object – It is used to create a physical connection with the database. It is instantiated every time by the SessionFactory object to interact with the database.
Transaction Object – It is used to handle the transaction works in the Hibernate framework.
Query Object – It is used to create objects or to retrieve data from the database using HQL or SQL.
Criteria Object – It is used to retrieve objects by executing the object-oriented criteria queries.
Q76. What is n+1 select problem in Hibernate?
The N+1 Selects is a problem related to the performance issue the Hibernate. In this problem, multiple queries are fired for a single query. Let's say that you have a collection of phone vendors and each vendor has a collection of phone models. To print all the phone models from each vendor, you’d have a query like the following,
Select * from Vendor; Select * from models where Vendor = ?;
Here we have one select query for fetching all vendors and another for selecting all the phone models from each vendor. We do the N+1 select query. It is an example of an N+1 problem in Hibernate. To avoid this, hibernate has an option that traces all the SQL queries to find the N+1 problem. Then, you can resolve this problem by firing a query that joins the two tables (vendor and phone models) and gets the result in a single query.
Q77. What is session in Hibernate?
A Session is an object in Hibernate that is used to create a physical connection with the database. This object is created each time when the database needs to be connected and interacted. After the connection with the database, the session object is destroyed as it is not a thread-safe.
It provides create, read, delete operations. The session object may be in a transient state, persistent state, or detached state.
Q78. What is difference between load() and get() in Hibernate?
The get and load method are both derived from the Hibernate Session class and are used to retrieve objects from the database.
But there is a difference in how they are retrieving the objects.
Session get method - This method returns the real object when it is not present in the session cache by fetching it from the database. If the object is not found, then the get method returns null. It may involve multiple round trips to the database that may not be effective in all the cases and also reduces the performance.
Session load method – This method returns a proxy when the real object is not in cache. It initialized the object only if a method other than getid() is called on persistent. It doesn’t always hit the database and returns a proxy. So, it offers better performance than the session get method.
Q79. Enlist different states of object in Hibernate?
In hibernate, Objects are represented in any one of the following three states,
Transient Object State – In this state, the object is not linked with any hibernate session and does not represent in any row of the database. An object is in the transient state if it is created for the first time with the new() operator. It doesn’t contain any primary key value and it will be collected into the garbage if no other object refers to it.
Persistent Object State – In this state, an object will be associated with the hibernate session. It represents a row in the database. It also has a primary key value. This object can be created by associating a transient object with the session.
Detached Object State – These are the objects that are removed from the hibernate session. These objects contain identity and changes made to these objects are not saved in the database. Also, persistence operation with the detached object is not possible.
Q80. What is Isolation and Propagation in Hibernate?
The Propagation and Isolation are parameters in the @Transactional annotation.
Propagation – It defines how transactions are related to each other. It has the following options,
Isolation – It defines the data contract between the transactions. It has options such as Read Uncommitted, Read Committed, Repeatable Read, and Serializable. Uncommitted allows dirty read. Read Uncommitted does not allow a dirty read. Serializable performs all actions in sequence. Repeatable Read results in the same if a row is read twice in the transaction.
Q81. What is criterion query in hibernate?
The Hibernate Criteria Query is one of the ways to retrieve data from the database in the hibernate framework. The criteria API is used to created complex nested queries in Java for executing database-related operations. It also includes compile-time syntax and QBE (Query By Example) functionality. With QBE, you can pass objects with properties to retrieve data from the database. It also has support for projection and aggregation methods.
Q82. What are annotations in Hibernate?
Annotations can be used in the hibernate framework to define the mapping. It can be used standalone or with XML to create the mapping. The hibernate annotations are based on the JPA 2 specification and are defined in javax.persistence package.
It provides a way to create the metadata for the relational table and object mapping. It is used to represent mapping information but it is not as flexible as XML mapping.
Q83. What are different types of mappings available in Hibernate?
The Hibernate Mapping types are declared and used in the mapping files. These types get converted from Java type to SQL type. There are many mapping types in Hibernate like primitive types, data and time types, binary types, and JDK related types.
Primitive types include integer, long, short, float, double, string, byte, Boolean, character, and big_decimal.
Date and time types include data, time, calendar, timestamp, and calendar_date.
Binary and Object types include binary, text, clob, blob, and serializable.
JDK-related types include class, locale, timezone, and currency.
Q84. How to perform Select, Update, and Delete Query in Hibernate?
HQL is similar to SQL but it is a database-independent query language.
For the Select operation in HQL, it is like reading an entity. To select all the columns in the database, use from Employee e;
//here we select all columns from the employee database.
To select a specific column using HQL,
Select e.employeeID from Employee e; //here we select only employee ID from the database.
For update operation HQL, use the ‘update’ statement.
update Employee e set e.salary = 3500 where e.employeeID = 1; // here we update the salary for an employee using an ID.
For delete operation in HQL, use the ‘delete’ statement.
delete from Employee e where e.employeeID = 1; //here we delete the employee record based on ID.
Q85. What are Generators in Hibernate?
The Generator class in the hibernate framework is used to create a unique ID for the persistent objects.
The hibernate framework has many generator classes. They are,
Q86. Explain Projections in Hibernate?
Projection in Hibernate is a class for creating projection objects. It is defined in “org.hibernate.criterion” package. It is used to query a subset of attributes of a group of entities.
It is also used to distinct clauses or aggregate functions like max, and sum.