Hibernate Interview Questions- Part 4

Hibernate is a helpful tool that saves developers time by handling database tasks behind the scenes. But in an interview, being able to explain how it works is just as important as using it. That’s where this guide can help. Inside, you’ll find straightforward Hibernate questions with answers written in plain English.
No tech jargon, no tricky explanations—just clear information that helps you learn faster and speak smarter. Whether you’re facing a phone screen or a technical round, this page will give you the tools to show what you know. Every question here is a step closer to landing the job you want.
Answer:
The following are a few advantages of criteria APIs:
- Criteria API helps to fetch entities from the database by using an object-oriented approach.
- It provides projections used for aggregate functions like min(), sum(), etc.
- You can write more dynamic & flexible queries as compared to HQL.
- It has the addOrder() method useful for ordering the results.
Answer:
The Criteria API helps developers to build dynamic criteria queries on the persistence database. It is a more flexible & powerful alternative to HQL queries for creating dynamic queries. It enables the programmatic development of criteria query objects. The org.hibernate.The Criteria interface is useful for such purposes. A Session interface of Hibernate has a createCriteria() method that takes the persistent object’s entity or class as the parameters & returns the persistence object instance where the criteria query is executed. It also makes it very easy to incorporate restrictions to retrieve data from the database selectively. It can be achieved through the add() method, which accepts the org.hibernate.criterion.Criterion object representing the individual restriction.
Answer:
Derived properties are those properties that are not mapped to a column of the database table. Such properties are also known as calculated properties which are calculated during runtime. Derived properties are read-only in nature & can be defined through @Formula annotation or tag in the hbm.xml definition file. To use the @Formula annotation, you need to import org. hibernate. annotations. Formula package.
Answer:
We can use extension interfaces in order to add any required functionality which isn’t supported by built-in interfaces.
Answer:
The N+1 problem refers to a performance issue in ORM that fires multiple select queries (N+1, wherein N is the no. of records in the table) in a database for a single select query at the application layer. Hibernate offers multiple ways to address the N+1 performance problem.
Answer:
Cascading is the persistent action involving an object propagating to other objects through an association. Cascading is typically transitive & applicable to several Hibernate actions. The cascade attribute of the annotation defines an association and says what actions should be cascaded for that association. It simply means that When we perform an action on the target entity, the same action will also apply to the associated entity.
Commonly used cascade types in Hibernate are:
- delete or remove
- detach or evict
- merge
- lock
- persist
- refresh
- replicate
- save_update or update
Answer:
The following are the steps to create hibernate projects in Eclipse:
- First, you need to create the Java project & download Hibernate from the website. When it shows up in your download library, hit hibernate & add jar files to it;
- Also, add MySQL JDBC driver to the file;
- Therein, Create a Persistent class with the mapping information;
- Once the persistence class is created, create the Hibernate Configuration file again;
- Then, create a Utility class to initialize the SessionFactory along with Example code to load data from the Database;
- After following the above, right-click on the mouse to RUN;
Answer:
There are several ways to implement the joins() in the Hibernate framework, such as using associations like one-to-one or one-to-many, join fetch method to load the associated data simultaneously & fire native SQL query with the ‘join’ keyword.
Answer:
Hibernate simplifies:
- Saving and retrieving your domain objects;
- Creating database column & table name changes;
- Centralizing the pre-save & post-retrieve logic;
- Complex joins for retrieving the related items;
- Schema creation from the object model
Answer:
The general communication flow of Hibernate with RDBMS is as follows:
- Load a Hibernate configuration file & create the configuration object that will automatically load all the HBM mapping files.
- Now, create a Session Factory from the configuration object.
- Get a session from the Session Factory.
- Create the HQL Query & execute Query to get the list of Java objects.
Answer:
Component mapping in Hibernate means mapping a dependent object as a component. A component is an object stored as a value instead of an entity reference. It is mainly used if the dependent object doesn’t have the primary key. The component mapping is mostly applicable to the composition of (HAS-A relation); this is why it is known as a component.
Answer:
Hibernate uses the fetching strategy to retrieve an associated object if the application needs to navigate the association. It can be declared in the O/R mapping metadata or overridden by a particular Criteria query or HQL.
Hibernate has four fetching strategies:
- Join fetching: This strategy disables lazy loading & always loads all the entities & collections.
- Select fetching: It lazy loads all the collections and entities.
- Sub-select fetching: This fetching strategy groups its collection into the sub-select statement.
- Batch fetching: It means fetching up to ‘N’ entities or collections, *Not record*.
Answer:
Dirty Checking is one of the Hibernate features. In dirty checking, hibernate automatically detects if an object is modified or not and further checks if it needs to be updated. As long as the object is in the persistent state, it is bound to a particular Session(org.hibernate.Session). Hibernate monitors the changes to the objects & executes SQL.
Answer:
Hibernate tries to defer the Persistence Context flushing to the last moment. It has been traditionally known as the transactional write-behind. The write-behind is more related to the Hibernate flushing instead of any logical or physical transaction.
Answer:
Callback interfaces are used in the application to get a notification when some object events occur. When the object is saved, loaded, or deleted, there is no need to implement callbacks into the Hibernate applications. However, callbacks are useful for implementing certain types of generic functionalities. The callback interface in Hibernate mainly helps with receiving notifications of different events from the object.
Answer:
- @NotNull- CharSequence, Map, Array, or Collection object cannot be null but can be empty.
- @NotEmpty- CharSequence, Map, Collection or Array object cannot be null & empty (size > 0).
- @NotBlank- String isn’t null & the length is greater than zero.
Answer:
In applications with long-running transactions, optimistic locking provides the required scalability. Without an optimistic locking, the table gets locked & avoids concurrent access. Hibernate offers two approaches to obtain optimistic locking, i.e., timestamp or version number. The latter one is preferred & implemented by using @Version annotation. An entity manager deploys the LOCKING_COLUMN to detect any conflicting updates.
Answer:
Lazy fetching determines whether to load a Child Object when loading a Parent Object. The lazy loading of Child Objects is true by default. One needs to ensure that the child objects are not loaded until they are explicitly invoked in an application by calling the getChild() method on the parent. In such a case, hibernate issues a fresh database call to load a child when getChild() is actually called on the Parent Object. However, in some cases, you need to load the child objects when the parent is loaded. Hibernate will load the child when a parent is loaded from a database by making lazy=false.
Answer:
Version checking is used in the Hibernate Framework when two or more threads try to access the same data. One can prevent slate object updating in Hibernate by using the version-checking method. Check the version of a row where updating is taking place & get the row version when the row TABLE is fetched for an update. At updating time, version no. is fetched & matched with the version number fetched at the time of fetching.
Answer:
save Or Update is more flexible in terms of usage, but it involves extra processing to find whether the record already exists in the table or not. The save Or Update method does a selection first to decide if it needs to do an update or insert. It will insert data if the primary key does not exist; otherwise, it will update data.