• +91 9723535972
  • info@interviewmaterial.com

Hibernate Interview Questions and Answers

Hibernate Interview Questions and Answers

Question - 81 : - Difference between the transient, persistent and detached state in Hibernate?

Answer - 81 : -

  • Transient state: New objects are created in the Java program but are not associated with any Hibernate Session.
  • Persistent state: An object which is associated with a Hibernate session is called Persistent object. While an object which was earlier associated with Hibernate session but currently it’s not associate is known as a detached object. You can call save() or persist() method to store those object into the database and bring them into the Persistent state.
  • Detached state: You can re-attach a detached object to Hibernate sessions by calling either update() or saveOrUpdate() method.

Question - 82 : -
Difference between sorted and ordered collection in Hibernate?

Answer - 82 : -

sorted collection sort the data in JVM’s heap memory using Java’s collection framework sorting methods. The ordered collection is sorted using order by clause in the database itself.

Question - 83 : - Difference between save() and saveOrUpdate() method of Hibernate?

Answer - 83 : -

Even though save() and saveOrUpdate() method is used to store an object into Database, the key difference between them is that save() can only Insert records but saveOrUpdate() can either Insert or Update records.

Question - 84 : - What happens when the no-args constructor is absent in the Entity bean?

Answer - 84 : -

Hibernate framework internally uses Reflection API for creating entity bean instances when get() or load() methods are called. The method Class.newInstance() is used which requires a no-args constructor to be present. When we don't have this constructor in the entity beans, then hibernate fails to instantiate the bean and hence it throws HibernateException.

Question - 85 : - Can we declare the Entity class final?

Answer - 85 : -

No, we should not define the entity class final because hibernate uses proxy classes and objects for lazy loading of data and hits the database only when it is absolutely needed. This is achieved by extending the entity bean. If the entity class (or bean) is made final, then it cant be extended and hence lazy loading can not be supported.

Question - 86 : - Explain Query Cache

Answer - 86 : -

Hibernate framework provides an optional feature called cache region for the queries’ resultset. Additional configurations have to be done in code in order to enable this. The query cache is useful for those queries which are most frequently called with the same parameters. This increases the speed of the data retrieval and greatly improves performance for commonly repetitive queries.

This does not cache the state of actual entities in the result set but it only stores the identifier values and results of the value type. Hence, query cache should be always used in association with second-level cache.

Configuration:

In the hibernate configuration XML file, set the use_query_cache property to true as shown below:

true

In the code, we need to do the below changes for the query object:
Query query = session.createQuery("from InterviewBitEmployee");
query.setCacheable(true);
query.setCacheRegion("IB_EMP");

Question - 87 : - Can you tell something about the N+1 SELECT problem in Hibernate?

Answer - 87 : -

N+1 SELECT problem is due to the result of using lazy loading and on-demand fetching strategy. Let's take an example. If you have an N items list and each item from the list has a dependency on a collection of another object, say bid. In order to find the highest bid for each item while using the lazy loading strategy, hibernate has to first fire 1 query to load all items and then subsequently fire N queries to load big of each item. Hence, hibernate actually ends up executing N+1 queries.

Question - 88 : - How to solve N+1 SELECT problem in Hibernate?

Answer - 88 : -

Some of the strategies followed for solving the N+1 SELECT problem are:

Pre-fetch the records in batches which helps us to reduce the problem of N+1 to (N/K) + 1 where K refers to the size of the batch.
Subselect the fetching strategy
As last resort, try to avoid or disable lazy loading altogether.

Question - 89 : - What are the concurrency strategies available in hibernate?

Answer - 89 : -

Concurrency strategies are the mediators responsible for storing and retrieving items from the cache. While enabling second-level cache, it is the responsibility of the developer to provide what strategy is to be implemented to decide for each persistent class and collection.

Following are the concurrency strategies that are used:

  • Transactional: This is used in cases of updating data that most likely causes stale data and this prevention is most critical to the application.
  • Read-Only: This is used when we don't want the data to be modified and can be used for reference data only.
  • Read-Write: Here, data is mostly read and is used when the prevention of stale data is of critical importance.
  • Non-strict-Read-Write: Using this strategy will ensure that there wouldn't be any consistency between the database and cache. This strategy can be used when the data can be modified and stale data is not of critical concern.

Question - 90 : - What is Single Table Strategy?

Answer - 90 : -

Single Table Strategy is a hibernate’s strategy for performing inheritance mapping. This strategy is considered to be the best among all the other existing ones. Here, the inheritance data hierarchy is stored in the single table by making use of a discriminator column which determines to what class the record belongs.

For the example defined in the Hibernate Inheritance Mapping question above, if we follow this single table strategy, then all the permanent and contract employees’ details are stored in only one table called InterviewBitEmployee in the database and the employees would be differentiated by making use of discriminator column named employee_type.

Hibernate provides @Inheritance annotation which takes strategy as the parameter. This is used for defining what strategy we would be using. By giving them value, InheritanceType.SINGLE_TABLE signifies that we are using a single table strategy for mapping.

@DiscriminatorColumn is used for specifying what is the discriminator column of the table in the database corresponding to the entity.
@DiscriminatorValue is used for specifying what value differentiates the records of two types.
The code snippet would be like this:

InterviewBitEmployee class:

@Entity
@Table(name = "InterviewBitEmployee")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "employee_type")
@NoArgsConstructor
@AllArgsConstructor
public class InterviewBitEmployee {
   @Id
   @Column(name = "employee_id")
   private String employeeId;
   private String fullName;
   private String email;
}
InterviewBitContractEmployee class:

@Entity
@DiscriminatorValue("contract")
@NoArgsConstructor
@AllArgsConstructor
public class InterviewBitContractEmployee extends InterviewBitEmployee {
   private LocalDate contractStartDate;
   private LocalDate contractEndDate;
   private String agencyName;
}
InterviewBitPermanentEmployee class:

@Entity
@DiscriminatorValue("permanent")
@NoArgsConstructor
@AllArgsConstructor
public class InterviewBitPermanentEmployee extends InterviewBitEmployee {
   private LocalDate workStartDate;
   private int numberOfLeaves;
}


NCERT Solutions

 

Share your email for latest updates

Name:
Email:

Our partners