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.

Does Hibernate support Native SQL Queries?

Answer»

Yes, it does. HIBERNATE provides the createSQLQuery() METHOD to let a developer call the native SQL statement directly and returns a Query object.

Consider the example where you want to get employee data with the full name “Hibernate”. We don’t want to use HQL-based features, instead, we want to write our own SQL QUERIES. In this case, the code would be:

Query query = session.createSQLQuery( "select * from interviewbit_employee ibe where ibe.fullName = :fullName") .addEntity(InterviewBitEmployee.class) .setParameter("fullName", "Hibernate"); //named parametersList result = query.list();

Alternatively, native queries can also be supported when USING NamedQueries.

2.

Can you tell the difference between setMaxResults() and setFetchSize() of Query?

Answer»

setMaxResults() the function works similar to LIMIT in SQL. Here, we set the maximum NUMBER of rows that we want to be returned. This method is implemented by all database drivers.

setFetchSize() works for optimizing how Hibernate sends the result to the CALLER for example: are the RESULTS BUFFERED, are they sent in different SIZE chunks, etc. This method is not implemented by all the database drivers.

3.

Collection mapping can be done using One-to-One and Many-to-One Associations. What do you think?

Answer»

FALSE, COLLECTION MAPPING is POSSIBLE only with One-to-Many and Many-to-Many ASSOCIATIONS.

4.

When is merge() method of the hibernate session useful?

Answer»

Merge() method can be used for updating EXISTING values. The specialty of this method is, once the existing values are updated, the method creates a copy from the entity object and returns it. This RESULT object goes into the persistent context and is then tracked for any changes. The object that was INITIALLY used is not tracked.

5.

What is hibernate caching?

Answer»

Hibernate caching is the strategy for improving the application performance by pooling objects in the cache so that the queries are EXECUTED faster. Hibernate caching is particularly useful when fetching the same data that is executed multiple times. Rather than hitting the database, we can just access the data from the cache. This results in REDUCED throughput time of the application.

Types of Hibernate Caching

First Level Cache:

  • This level is enabled by default.
  • The first level cache resides in the hibernate session object.
  • Since it belongs to the session object, the scope of the data stored here will not be AVAILABLE to the entire application as an application can MAKE use of multiple session objects.
First Level Caching

Second Level Cache:

  • Second level cache resides in the SessionFactory object and due to this, the data is accessible by the entire application.
  • This is not available by default. It has to be enabled explicitly.
  • EH (EASY Hibernate) Cache, Swarm Cache, OS Cache, JBoss Cache are some example cache providers.
Second Level Caching
6.

What does session.lock() method in hibernate do?

Answer»

session.lock() method is used to REATTACH a detached object to the session. session.lock() method does not check for any data synchronization between the database and the object in the PERSISTENCE context and hence this reattachment MIGHT LEAD to loss of data synchronization.

7.

What are Many to Many associations?

Answer»

Many-to-many association INDICATES that there are multiple relations between the instances of two entities. We could take the example of multiple students taking part in multiple courses and vice versa.

Since both the student and course entities refer to each other by MEANS of foreign keys, we represent this relationship TECHNICALLY by creating a separate table to HOLD these foreign keys.

Many To Many Associations

Here, Student-Course Table is called the Join Table where the student_id and course_id would form the composite primary key.

8.

Can you tell something about one to many associations and how can we use them in Hibernate?

Answer»

The one-to-many association is the most commonly used which indicates that one object is linked/associated with multiple objects.

For example, one PERSON can own multiple cars.

Hibernate One To Many Mapping

In Hibernate, we can achieve this by using @OnetoMany of JPA ANNOTATIONS in the model classes. Consider the above example of a person having multiple cars as SHOWN below:

@Entity@Table(name="Person")PUBLIC class Person { //... @OneToMany(mappedBy="owner") private Set<Car> cars; // getters and setters}

In the Person class, we have defined the car's property to have @OneToMany association. The Car class would have owned property that is used by the mappedBy variable in the Person class. The Car class is as shown below:

@Entity@Table(name="Car")public class Car { // Other Properties @ManyToOne @JoinColumn(name="person_id", nullable=false) private Person owner; public Car() {} // getters and setters}

@ManyToOne annotation indicates that many INSTANCES of an entity are mapped to one instance of another entity – many cars of one person.

9.

What is HQL?

Answer»

Hibernate Query Language (HQL) is used as an extension of SQL. It is very simple, EFFICIENT, and very flexible for performing complex operations on relational databases without writing complicated queries. HQL is the object-oriented representation of query language, i.e instead of using table name, we MAKE use of the class name which makes this language independent of any database.

This makes use of the Query interface provided by Hibernate. The Query object is obtained by calling the createQuery() method of the hibernate Session interface.

Following are the most commonly used methods of query interface:

  • public int executeUpdate() : This method is used to RUN the update/delete query.
  • public List list(): This method returns the result as a list.
  • public Query setFirstResult(int rowNumber): This method ACCEPTS the row number as the PARAMETER using which the record of that row number would be retrieved.
  • public Query setMaxResult(int rowsCount): This method returns a maximum up to the specified rowCount while retrieving from the database.
  • public Query setParameter(int position, Object value): This method sets the value to the attribute/column at a particular position. This method follows the JDBC style of the query parameter.
  • public Query setParameter(String name, Object value): This method sets the value to a named query parameter.

Example: To get a list of all records from InterviewBitEmployee Table:

Query query=session.createQuery("from InterviewBitEmployee"); List<InterviewBitEmployee> list=query.list(); System.out.println(list.get(0));
10.

What is criteria API in hibernate?

Answer»

Criteria API in Hibernate helps developers to build dynamic criteria queries on the persistence database. Criteria API is a more powerful and flexible alternative to HQL (Hibernate Query Language) queries for creating dynamic queries.

This API allows to programmatically development criteria query objects. The org.hibernate.Criteria interface is used for these purposes. The Session interface of hibernate framework has createCriteria() METHOD that takes the persistent object’s class or its entity name as the parameters and returns persistence object instance the criteria query is executed.

It also makes it very easy to incorporate restrictions to selectively retrieve data from the database. It can be achieved by using the add() method which accepts the org.hibernate.criterion.Criterion object representing individual restriction.

Usage examples:

To return all the data of InterviewBitEmployee entity class.

Criteria criteria = session.createCriteria(InterviewBitEmployee.class);List<InterviewBitEmployee> results = criteria.list();

To retrive objects whose property has value equal to the restriction, we use Restrictions.eq() method. For example, to fetch all records with name ‘Hibernate’:

Criteria criteria= session.createCriteria(InterviewBitEmployee.class);criteria.add(Restrictions.eq("fullName","Hibernate"));List<InterviewBitEmployee> results = criteria.list();

To get objects whose property has the value “not equal to” the restriction, we use Restrictions.ne() method. For example, to fetch all the records whose employee’s name is not Hibernate:

Criteria criteria= session.createCriteria(InterviewBitEmployee.class);criteria.add(Restrictions.ne("fullName","Hibernate"));List<Employee> results = criteria.list()

To retrieve all objects whose property matches a given PATTERN, we use Restrictions.like() (for CASE sensitivenes) and Restrictions.ilike()(for case insensitiveness)

Criteria criteria= session.createCriteria(InterviewBitEmployee.class);criteria.add(Restrictions.like("fullName","Hib%",MatchMode.ANYWHERE));List<InterviewBitEmployee> results = criteria.list();

Similarly, it also has other methods like isNull(), isNotNull(), gt(), ge(), lt(), le() etc for adding more varieties of restrictions. It has to be noted that for Hibernate 5 onwards, the functions returning an object of typeCriteria are deprecated. Hibernate 5 VERSION has provided interfaces like CriteriaBuilder and CriteriaQuery to serve the purpose:

javax.persistence.criteria.CriteriaBuilderjavax.persistence.criteria.CriteriaQuery// Create CriteriaBuilderCriteriaBuilder builder = session.getCriteriaBuilder();// Create CriteriaQueryCriteriaQuery<YourClass> criteria = builder.createQuery(YourClass.class);

For introducing restrictions in CriteriaQuery, we can use the CriteriaQuery.where method which is analogous to using the WHERE clause in a JPQL query.

11.

Differentiate between get() and load() in Hibernate session

Answer»

These are the methods to get data from the database. The primary DIFFERENCES between get and load in Hibernate are given below:

get()load()
This method GETS the data from the database as soon as it is called.This method returns a proxy object and loads the data only when it is required.
The database is hit every time the method is called.The database is hit only when it is really NEEDED and this is called Lazy Loading which makes the method better.
The method returns NULL if the object is not found.The method throws ObjectNotFoundException if the object is not found.
This method should be used if we are unsure about the EXISTENCE of data in the database.This method is to be used when we know for sure that the data is present in the database.
12.

Differentiate between save() and saveOrUpdate() methods in hibernate session.

Answer»

Both the methods save records to the table in the database in case there are no records with the primary key in the table. However, the main differences between these two are listed below:

save()saveOrUpdate()
save() generates a new IDENTIFIER and INSERT RECORD into a databaseSession.saveOrUpdate() can either INSERT or UPDATE based upon existence of a record.
The insertion fails if the primary key ALREADY exists in the table.In case the primary key already exists, then the record is updated.
The return type is Serializable which is the newly generated identifier ID value as a Serializable object.The return type of the saveOrUpdate() method is void.
This method is used to bring only a transient object to a persistent state.This method can bring both transient (new) and detached (existing) objects into a persistent state. It is often used to re-attach a detached object into a Session

Clearly, saveOrUpdate() is more flexible in terms of use but it involves extra processing to find out whether a record already exists in the table or not.

13.

Can you tell the difference between getCurrentSession and openSession methods?

Answer»

Both the METHODS are provided by the Session Factory. The main differences are given below:

getCurrentSession()openSession()
This method returns the session bound to the context.This method always opens a new session.
This session object scope belongs to the hibernate context and to make this work hibernate configuration file has to be modified by adding <property name = "hibernate.current_session_context_class"> thread </property>. If not added, then using the method WOULD throw an HibernateException.A new session object has to be created for each request in a multi-threaded environment. Hence, you NEED not configure any property to call this method.
This session object gets closed once the session factory is closed.It's the developer’s responsibility to close this object once all the database OPERATIONS are done.
In a SINGLE-threaded environment, this method is faster than openSession().In single threaded environment, it is slower than getCurrentSession()single-threadeda 

Apart from these two methods, there is another method openStatelessSession() and this method returns a stateless session object.

14.

Explain Hibernate architecture

Answer»

The Hibernate architecture consists of MANY objects such as a persistent object, session factory, session, query, transaction, etc. Applications developed using Hibernate is MAINLY categorized into 4 parts:

  • Java Application
  • Hibernate framework - Configuration and Mapping Files
  • Internal API -
    • JDBC (Java Database Connectivity)
    • JTA (Java Transaction API)
    • JNDI (Java Naming Directory Interface).
  • Database - MySQL, PostGreSQL, Oracle, etc
Hibernate Architecture

 

The main elements of Hibernate framework are:

  • SessionFactory: This provides a factory method to get session objects and clients of ConnectionProvider. It holds a second-level cache (OPTIONAL) of data.
  • Session: This is a short-lived object that acts as an interface between the java application objects and database data.
    • The session can be used to generate transaction, query, and criteria objects.
    • It also has a mandatory first-level cache of data.
  • Transaction: This object specifies the atomic unit of work and has methods USEFUL for transaction management. This is optional.
  • ConnectionProvider: This is a factory of JDBC connection objects and it provides an ABSTRACTION to the application from the DriverManager. This is optional.
  • TransactionFactory: This is a factory of Transaction objects. It is optional.
Hibernate Objects
15.

What are the most commonly used annotations available to support hibernate mapping?

Answer»

Hibernate framework provides support to JPA annotations and other useful annotations in the org.hibernate.annotations package. Some of them are as follows:

  • javax.persistence.Entity: This annotation is used on the model classes by using “@Entity” and tells that the classes are entity beans.
  • javax.persistence.Table: This annotation is used on the model classes by using “@Table” and tells that the class maps to the table name in the database.
  • javax.persistence.Access: This is used as “@Access” and is used for defining the access type of EITHER field or PROPERTY. When nothing is specified, the default value taken is “field”.
  • javax.persistence.Id: This is used as “@Id” and is used on the attribute in a class to indicate that attribute is the primary key in the bean entity.
  • javax.persistence.EmbeddedId: Used as “@EmbeddedId” UPON the attribute and indicates it is a composite primary key of the bean entity.
  • javax.persistence.Column: “@Column” is used for defining the column name in the database table.
  • javax.persistence.GeneratedValue: “@GeneratedValue” is used for defining the strategy used for primary key generation. This annotation is used along with javax.persistence.GenerationType enum.
  • javax.persistence.OneToOne: “@OneToOne” is used for defining the one-to-one mapping between two bean entities. Similarly, hibernate provides OneToMany, ManyToOne and ManyToMany annotations for defining different mapping types.
    org.hibernate.annotations.CASCADE: “@Cascade” annotation is used for defining the cascading action between two bean entities. It is used with org.hibernate.annotations.CascadeType enum to define the type of cascading.
    Following is a sample class where we have used the above listed annotations:
package com.dev.interviewbit.model;import javax.persistence.Access;import javax.persistence.AccessType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.OneToOne;import javax.persistence.Table;import org.hibernate.annotations.Cascade;@Entity@Table(name = "InterviewBitEmployee")@Access(value=AccessType.FIELD)public class InterviewBitEmployee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "employee_id") private long id; @Column(name = "full_name") private STRING fullName; @Column(name = "email") private String email; @OneToOne(mappedBy = "employee") @Cascade(value = org.hibernate.annotations.CascadeType.ALL) private Address address; //getters and setters methods}
16.

Explain hibernate mapping file

Answer»

Hibernate mapping file is an XML file that is used for defining the entity bean fields and corresponding database column mappings.
These files are useful when the project uses third-party classes where JPA annotations provided by hibernating cannot be used.

In the previous example, we have defined the mapping resource as “InterviewBitEmployee.hbm.xml” in the config file. Let us SEE what that sample hbm.xml file looks like:

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN""HTTP://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping> <!-- What class is mapped to what database table--> <class name = "InterviewBitEmployee" table = "InterviewBitEmployee"> <meta attribute = "class-description"> This class CONTAINS the details of employees of InterviewBit. </meta> <ID name = "id" type = "INT" column = "employee_id"> <generator class="native"/> </id> <property name = "fullName" column = "full_name" type = "string"/> <property name = "email" column = "email" type = "string"/> </class></hibernate-mapping>