Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

What are the benefits of NamedQuery?

Answer»

In order to understand the benefits of NamedQuery, let's first understand the disadvantage of HQL and SQL. The main disadvantage of having HQL and SQL scattered across data access objects is that it makes the code unreadable. Hence, as good practice, it is recommended to group all HQL and SQL codes in ONE place and use only their reference in the actual data access code. In order to achieve this, Hibernate gives US NAMED queries.

A named query is a statically defined query with a predefined unchangeable query string. They are validated when the session factory is created, THUS making the application fail fast in case of an error.

Conclusion

Hibernate is the most powerful open source ORM tool that is used for mapping java objects with the database structures at run time. It has become more popular among software DEVELOPERS due to its nature of abstraction allowing developers to continue application development by being database independent and focus just on the application business logic.

Additional Resources

Practice Coding

Java Tutorials

Java Interview Questions

2.

Can you tell something about Named SQL Query

Answer»

A named SQL query is an expression represented in the form of a table. Here, SQL expressions to select/retrieve rows and columns from one or more tables in one or more DATABASES can be specified. This is like using aliases to the queries.

In hibernate, we can make use of @NameQueries and @NameQuery annotations.

  • @NameQueries annotation is used for defining MULTIPLE named queries.
  • @NameQuery annotation is used for defining a single named query.

Code Snippet: We can define Named Query as shown below

@NamedQueries( { @NamedQuery( name = "findIBEmployeeByFullName", query = "from InterviewBitEmployee e where e.fullName = :fullName" ) } )

:fullName REFERS to the parameter that is programmer defined and can be set using the query.setParameter method while using the named query.

Usage:

TypedQuery query = session.getNamedQuery("findIBEmployeeByFullName"); query.setParameter("fullName","Hibernate"); List<InterviewBitEmployee> ibEmployees = query.getResultList();

The getNamedQuery method TAKES the name of the named query and returns the query instance.

3.

Can you tell something about Table Per Class Strategy.

Answer»

Table Per Class Strategy is another type of inheritance mapping strategy where each class in the hierarchy has a corresponding mapping database table. For example, the InterviewBitContractEmployee class details are stored in the interviewbit_contract_employee table and InterviewBitPermanentEmployee class details are stored in interviewbit_permanent_employee tables respectively. As the data is stored in different tables, there will be no need for a discriminator column as done in a single table strategy.

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.TABLE_PER_CLASS, it signifies that we are using a table per class strategy for mapping.

The code snippet will be as shown below:

InterviewBitEmployee class:

@Entity(name = "interviewbit_employee")@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)@NoArgsConstructor@AllArgsConstructorpublic class InterviewBitEmployee { @Id @Column(name = "employee_id") private String employeeId; private String fullName; private String email;}

InterviewBitContractEmployee class:

@Entity(name = "interviewbit_contract_employee")@Table(name = "interviewbit_contract_employee")@NoArgsConstructor@AllArgsConstructorpublic class InterviewBitContractEmployee EXTENDS InterviewBitEmployee { private LocalDate contractStartDate; private LocalDate contractEndDate; private String agencyName;}

InterviewBitPermanentEmployee class:

@Entity(name = "interviewbit_permanent_employee")@Table(name = "interviewbit_permanent_employee")@NoArgsConstructor@AllArgsConstructorpublic class InterviewBitPermanentEmployee extends InterviewBitEmployee { private LocalDate workStartDate; private int numberOfLeaves;}

Disadvantages:

  • This type of strategy offers less performance due to the need for additional joins to get the data.
  • This strategy is not supported by all JPA providers.
  • ORDERING is tricky in some cases since it is done based on a class and later by the ordering criteria.
4.

What is Single Table Strategy?

Answer»

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@AllArgsConstructorpublic class InterviewBitEmployee { @Id @Column(name = "employee_id") PRIVATE String employeeId; private String fullName; private String email;}

InterviewBitContractEmployee class:

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

InterviewBitPermanentEmployee class:

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

What are the concurrency strategies available in hibernate?

Answer»

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.
6.

How to solve N+1 SELECT problem in Hibernate?

Answer»

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.
7.

Can you tell something about the N+1 SELECT problem in Hibernate?

Answer»

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.

8.

Explain Query Cache

Answer»

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:

<property name="hibernate.cache.use_query_cache">true</property>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");
9.

What are the states of a persistent entity?

Answer»

A persistent ENTITY can exist in any of the following states:

Transient:

  • This state is the initial state of any entity OBJECT.
  • Once the instance of the entity class is created, then the object is said to have entered a transient state. These objects exist in heap memory.
  • In this state, the object is not linked to any session. Hence, it is not related to any database due to which any changes in the data object don't affect the data in the database.
InterviewBitEmployee employee=new InterviewBitEmployee(); //The object is in the transient state. employee.setId(101); employee.setFullName("Hibernate");  employee.setEmail("hibernate@interviewbit.com");

Persistent:

  • This state is entered whenever the object is linked or associated with the session.
  • An object is said to be in a persistence state whenever we save or persist an object in the database. Each object corresponds to the row in the database table. Any modifications to the data in this state cause changes in the record in the database.

Following methods can be used upon the persistence object:

session.save(record); session.persist(record); session.update(record); session.saveOrUpdate(record); session.lock(record); session.merge(record);

Detached:

  • The object enters this state whenever the session is CLOSED or the cache is cleared.
  • Due to the object being no longer part of the session, any changes in the object will not reflect in the corresponding row of the database. However, it would still have its representation in the database.
  • In case the developer wants to persist changes of this object, it has to be reattached to the hibernate session.
  • In order to achieve the reattachment, we can use the methods load(), merge(), refresh(), update(), or save() methods on a new session by USING the reference of the detached object.

The object enters this state whenever any of the following methods are CALLED:

session.close();session.clear();session.detach(record);session.evict(record);Persistent Entity
10.

Can we declare the Entity class final?

Answer»

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.

11.

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

Answer»

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.