Hibernate Interview Questions And Answers

In this post, we will see Hibernate and JPA interview questions and answers.

Table of Contents

What is Hibernate and what do you understand by ORM?

Hibernate is a framework which is used to communicate the java application to the database. Hibernate is an ORM tool. ORM stands for Object Relational Mapping which maps the object(entity) to data stored in the database.

Entity mapped with database table and columns

See more details here.

What are the features and benefits of Hibernate?

  • Hibernate is a database-independent language. For example, supposes initially we have implemented MySql database and later if we want to use the Oracle database then no need to change java code.
  • Hibernate provides the facility to create database table automatically.
  • Hibernate support inheritance and association mapping.
  • In hibernate, all exceptions are the unchecked exception. So no need to handle at compile time using try-catch or throws keyword.
  • Hibernate provides the facility to generate primary keys automatically during storing the data into the database.
  • Hibernate has predefined API for pagination support.
  • Hibernate supports HQL, Criteria Query etc predefined API which can be directly used to retrieve the data from the database.
  • Hibernate provides a large number of API can be directly used to develop java application faster and easier. It reduces the boiler-plate code.

See all points in details with an example here.

What is the difference between JPA and Hibernate? Can we use JPA alone?

JPA is just specification and it does not have any implementation. Whereas hibernate is the implementation of those specifications.

JPA can’t do anything alone since it is just specification. It must be used either with Hibernate or EclipseLink or TopLink.

Below are the some JPA combinations.

JPA  + Hibernate(most popular).

JPA + TopLink

JPA + Eclipselink

JPA + JDO

Note –  Just for understanding purpose think JPA is an interface and  Hibernate is an implementation class of that interface.

public interface Jpa {
void m1();
}

class Hibernate {
public void m1() {
// some implementation logic
}
}

See more about JPA vs Hibernate here in details.

The benefit of using JPA is we can easily switch hibernate to TopLink and vice versa.

 

What is Hibernate configuration file?

We provide database related information in the hibernate configuration file. By default, Hibernate tries to find the file with name hibernate.cfg.xml. The configuration file used to create the Configuration class object. Using the Configuration class object further we can get SessionFactory reference.

Sample example of hibernate.cfg.xml.

<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">SYSTEM</property>
<property name="connection.password">oracle</property>
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="onetomany.Book" />
<mapping class="onetomany.Story" />
</session-factory>
</hibernate-configuration>

See more details about hibernate.cfg.xml here.

What is Hibernate mapping file?

Hibernate mapping file is used to map java object to the database table. The mapping file contains information about entity/POJO class and database table and column information.

Consider we have an entity called Book.java.

class Book {
private int bookId;
private String bookName;
//getter & setter

}

Sample book.hbm.xml file above entity.

<hibernate-mapping>
<class name="com.javatute.Book" table="BOOK">
<id name="bookId" column="book_id" type="java.lang.Integer" />
<property name="bookName" column="book_name" type="string" />
</class>
</hibernate-mapping>

Note –  This mapping should configure in hibernate.cfg.xml as below.

<hibernate-configuration>
<session-factory>

.
.
<mapping class="com.javatute.Book" />
</session-factory>
</hibernate-configuration>

What are the possible values of hbm2ddl.auto?

There are four possible value of  hbm2ddl.auto
1. validate – validate the table makes no changes in the database.
2. update – Update the existing table, if the table is not there create a new one.
3. create – first it will drop the existing table then it will create a new one.
4. create-drop – Drop the existing table when SessionFactory is closed explicitly.

What is SessionFactory in hibernate?

SessionFactory is an interface available in org.hibernate and provides factory methods to get the session object.

  • We can create a SessionFactory object using the Configuration class as below.

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

  • SessionFactory is Immutable. Once we create SessionFactory we can not modify it.
  • SessionFactory is created at the time of application startup, it reads all information from the configuration file(hibernate.cfg.xml file).
  • We should have one SessionFactory for one database configuration.
  • SessionFactory is thread-safe so multiple threads can access the SessionFactory at the same time.

See more details about SessionFactory here.

What is Session in hibernate?

The Session is an interface available in org.hibernate which provides different API to communicate java application to hibernate.

  • We can get the Session object using SessionFactory.

Session session = sessionFactory.openSession()

  • The main use of the Session object to perform create, get and delete operations for java classes(entity).
  • We can have multiple sessions for a SessionFactory.

See more details about Session here.

What is the architechture of Hibernate?

architecture of Hibernate

Configuration – The Configuration class reads information from the configuration file (hibernate.cfg.xml or another configuration file) and create a Configuration object.

Configuration configuration = new Configuration().configure("hibernate.cfg.xml");

SessionFactory and Session – We have already seen about SessionFactory and Session.

Transaction –We can get a Transaction reference using the session object.

Transaction tx = session.beginTransaction();

Persistent Objects – The Entity or POJO are persistent objects. We need to configure these classes in hibernate.hbm.xml file or we can annotate that class with @Entity annotation.

ConnectionProvider – ConnectionProvider is a way to obtain JDBC connections.

TransactionFactory – Factory for Transaction instances.

What are the important classes and interfaces in Hibernate?

  • Configuration
  • SessionFactory
  • Session
  • Query
  • Criteria
  • Transaction

Write a program save an entity in Hibernate?

  • Define entity Book.java
  • Define hibernate.cfg.xml file
  • Get the session object and use session.save.

Book.java

package hibernateannotation;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "book")
public class Book {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int bookId;

	@Column(name = "book_name")
	private String bookName;

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public int getBookId() {
		return bookId;
	}

	public void setBookId(int bookId) {
		this.bookId = bookId;
	}

}

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">SYSTEM</property>
<property name="connection.password">oracle3</property>
 
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
 
<mapping class="hibernateannotation.Book" />
 
</session-factory>
</hibernate-configuration>

HibernateSaveEntityExample.java

package hibernateannotation;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateSaveEntityExample {

	public static void main(String[] args) {

		Session session = null;
		try {
			Configuration cfg = new Configuration().configure();
			SessionFactory factory = cfg.buildSessionFactory();
			session = factory.openSession();
			Book book = new Book();
			book.setBookId(109);
			book.setBookName("Rich Dad Poor Dad");
			Transaction transaction = session.beginTransaction();
			session.save(book);
			System.out.println("Hello! Book object has been saved");
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();

		}

	}
}

Output at the console.

Hello! Book object has been saved
Hibernate: insert into book (book_name, bookId) values (?, ?)

What are the possible reasons for org.hibernate.MappingException: Unknown entity: packagename.EntityName?

As exception name suggest hibernate is not able to find the entity. There are many reasons for this.

First reason – If we forget to define <mapping class="hibernateannotation.Book" /> in hibernate.cfg.xml file.

Second reason – If we use org.hibernate.annotations.Entity instead of javax.persistence.Entity.

Note -We should avoid org.hibernate.annotations.Entity as it is deprecated.  Instead, we should use  (javax.persistence.Entity).

Tell some important annotation used in Hibernate.

@Entity
@Table
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column

What are the different states of a persistent entity?

Transient
Persistent
Detached

How to make an entity detached in Hibernate?

What is inheritance mapping in hibernate?

Single Table Mapping or table per class.

  • In Single Table Inheritance for all classes/entities which are in an inheritance relationship, there will be the only one table.
  • @Inheritance(strategy=InheritanceType.SINGLE_TABLE) annotation is used with parent class.
  • Apart from the above annotation @DiscriminatorColumn and @DiscriminatorValue( used to distinguish one entity from another) used.

Example – @DiscriminatorColumn(name=”type”,discriminatorType=DiscriminatorType.STRING) and @DiscriminatorValue(value=”SOME_VALUE”).

See more details and example using Spring Boot and Oracle.

Table Per Subclass.

  • In Table Per Subclass Mapping, subclass mapped tables are related to parent class mapped table with the primary and foreign key relationship.
  • There will be a separate table for all entity.

See more details and example using Spring Boot and Oracle.

Table Per Concrete Class.

  • In table per concrete class mapping, it will create a separate table for each entity.
  • @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) is used with parent entity.
  • Table created for parent entity will have only parent attribute/column whereas child entity will have both parents as well as child attribute/column.

See more details and example using Spring Boot and Oracle.

What is association mapping in hibernate?

There are four types of assoication mapping in hibernate.

OneToOne Mapping.

  • One entity is associated with another entity in One to one relationship using @OneToOne annotation.
  • By default fetch type of @OneToOne is EAGER.

See more details about One To One Mapping using Spring Boot and Oracle here.

OneToMany Mapping.

  • In case of One To Many mapping one entity associated with multiple entities.
  • By default fetch type of @OneToMany is LAZY.

See more details about One To One Mapping using Spring Boot and Oracle here.

ManyToOne mapping.

  • Multiple entities associated with one entity.
  • By default fetch type of @OneToMany is EAGER.

See more details about Many To One Mapping using Spring Boot and Oracle here.

ManyToMany mapping.

  • There is separate table defined using @JoinTable annotation.
  • By default fetch type of @ManyToMany is EAGER.

See more details about Many To Many Mapping using Spring Boot and Oracle here.

What is the use of @ElementCollection annotation in Hibernate?

@ElementCollection annotation is used to map a collection of a basic type(String, Integer etc) and embeddable types(User Defined class for example Book.java).

See more about @ElementCollection using Spring Boot here.

What is the first level cache in Hibernate? How to configure the first level cache?

  • The first level cache is associated with the session object. The data in the first level cache stored as long as the session is open, once the session is closed all data stored in the first level cache would be lost.
  • The data in the first level cache stored in RAM(In-Memory).
  • In hibernate, first level cache is enabled by default. No need to do any additional configuration.
  • Using session.contains() we can know entity exists in cache or not.
  • Using session.clear() we can clear the first level cache.

See more about the first-level cache here.

What is the Second level cache in Hibernate? How to configure the second level cache?

There are following popular ways to configure the second-level cache.

Using hazelcast.

We can configure the second level cache using Hazelcast. See an example here.

Using EH Cache.

EhCache is also a popular way to implement a second-level cache. See an example here.

What are the primary key generation strategies in JPA?

What is the Cache concurrency strategy in Hibernate?

  • read-only
  • read-write
  • nonstrict-read-write
  • transactional

Tell something about @OrderBy annotation?

we use @OrderBy Annotation in Hibernate for Sorting purpose. @OrderBy is used with only collection type of filed(Generally in case of association mapping the field annotated with @OneToMany  or @ManyToMany or @ElementCollection annotation). Let’s see below code snippet.

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "student_id", referencedColumnName = "id")
@OrderBy("bookName")
private List<Book> bookList = new ArrayList<Book>();

What are the cascade types in Hibernate?

Hibernate provides below cascade types.

ALL
PERSIST
MERGE
REMOVE
REFRESH
SAVE_UPDATE
EVICT
DETACH
 
JPA provides below cascade types.
 
CascadeType.PERSIST
CascadeType.MERGE
CascadeType.REMOVE
CascadeType.DETACH
CascadeType.REFRESH
CascadeType.ALL
 
See more details about Hibernate/JPA cascade types in detail here.

What is Eager Vs Lazy loading in hibernate?

There are two fetch types.

FetchType.LAZY
FetchType.EAGER

We use the fetch type(Lazy and Eager loading) for association mapping.

  • OneToOne mapping.
  • OneToMany mapping.
  • ManyToOne mapping
  • ManyToMany mapping
  • ElementCollection(used for embeddable objects). See an example about @ElementCollection.

See a depth example about fetch type in hibernate/JPA here.

What is use @Temporal annotation?

The @Temporal annotation is used with fields/properties which is a type of Date or Calendar and there are three possible types we can have @Temporal(TemporalType.DATE), @Temporal(TemporalType.TIME) and @Temporal(TemporalType.TIMESTAMP).

@Column(name = "start_date")
@Temporal(TemporalType.DATE)
private Date bookStartDate;
	
@Column(name = "end_date")
@Temporal(TemporalType.TIMESTAMP)
private Date bookEndDate;

@Column(name = "published_date")
@Temporal(TemporalType.TIME)
private Date bookPublishedDate;

See more details and examples about @Temporal annotation here.

What is versioning in Hibernate?

@Version annotation used with field/attributes. When we create an entity for first the time the default version would be zero. When we update an entity version will increase by +1. The version is managed by Hibernate and we should not modify version logic.

@Entity
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	@Column(name = "student_name")
	private String studentName;

	@Column(name = "roll_number")
	private String rollNumber;
	
	@Column(name = "version")
	@Version
	private Long version;
	
}

See a detailed example of @Version annotation here.

How to retrieve data using Criteria in Hibernate?

We can use the Session createCriteria() method to get Criteria. If we are using JPA entityManager, we can Session from entityManager using unwrap() method.


    Criteria criteria=session.createCriteria(Student.class);
    List<Student> students = criteria.list();

Note – The createCriteria() method has been deprecated. JPA CriteriaBuilder has been introduced in JPA 2.0.

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Student> criteriaQuery = criteriaBuilder.createQuery(Student.class);
    criteriaQuery.from(Student.class);
    List<Student> students = entityManager.createQuery(criteriaQuery).getResultList();
    return students;

See the Complete tutorial about JPA CrteriaBuilder with an example here.

How to perform sorting using Criteria in Hibernate?

Consider we have an entity called Student.java

@Entity
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	@Column(name = "name")
	private String name;

	@Column(name = "roll_number")
	private String rollNumber;

	@Column(name = "university")
	String university;
}

We want to sort on the basis of name field.

	@Transactional
	public List<Student> findAll() {
		Session session = entityManager.unwrap(Session.class);

		Criteria criteria = session.createCriteria(Student.class);
		criteria.addOrder(Order.asc("name"));
		List<Student> studentList = criteria.list();
		return studentList;
	}

See the complete example here.

For association mapping, how to avoid duplicate elements while retrieving the records using Criteria?

Consider we have OneToMany or ManyToMany association in our application. We are trying to retrieve the entity and our query is returning duplicate results. How to resolve this?

We can use Criteria interafce setResultTransformer() method.

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

What is the difference between the Session’s get() and load() methods?

Get()Load()
As soon we call the get() method, it will hit the database and return the original object.The load() method returns a proxy object. It will not hit the database until we try to use that object(for example – access some property from the proxy object).
It returns null if no record is there in a database for the given identifier.It throws ObjectNotFound exception if no record is there in the database for a given identifier(if we try to access some property from the proxy object then only it will throw an exception).

See more details about both points here.

What is HQL in Hibenrate?

Hibernate query language is the database-independent language where we use entity name instead of table name and field name instead of the column name.

HQL is object-oriented that supports inheritance, polymorphism, and association.

Consider we have an entity called Student.java. We have some records in the Database.

@Entity
public class Student implements Serializable {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	@Column(name = "name")
	private String name;

	@Column(name = "roll_number")
	private String rollNumber;

	@Column(name = "university")
	private String university;

}

HQL to return all student records from the database.

        Query query=session.createQuery("from Student");  
        List<Student> students = query.list();

Another way to write-

Query query=session.createQuery("from Student student");

Note – Here Student is the entity name.

See a depth tutorial about HQL.

How to perform sorting using HQL?

Consider we have an entity called Student.java, that contains fields id, name, rollNumber, and university. We have 10 records in the database and want to sort them on basis of the name in ascending order.

      Query query=session.createQuery("from Student s ORDER BY s.name asc");
      List<Student> students = query.list();

See an example of Sorting using HQL in Hibernate using SPring boot and Oracle.

What is the difference between the Session’s save() and persist() method?

save()persist()
The return type of save() method is Serializable, returns generated id.The return type of persit() method is void.
The save() method is only supported by Hibernate i.e hibernate specific.The persist() method is supported by Hibernate as well as JPA EntityManager (In EntityManager persist() method has been defined).
If the id generation type is AUTO, using the save() method we can pass identifiers in the entity.If the id generation type is AUTO and we pass identifier in persist() method, it will throw detached entity passed to persist exception.

See more details about save() vs persit().

When do you use merge() and update() in Hibernate?

What is the fetch mode in Hibernate?

What is the flush mode in Hibernate?

How to configure the JNDI data source using JBOSS and Oracle.

What are the design patterns that have been used in Hibernate?

How to validate columns defined in the Entity?

What is difference between openSession(), getCurrentSession()  and  getCurrentSession()?

What is Dirty Checking in Hibernate?

If we modify Object’s field hibernate perform automatic dirty checking and fires update query and object/entity is automatically saved into the database once the transaction is committed.

See a detailed hibernate dirty checking tutorial.

What is Transaction Management in Hibernate?

See more details about Hibernate transaction management here.

What is the N+1 problem in Hibernate?

What is the use of @DynamicUpdate annotation in Hibernate?

What is the use of orphan removal true in Hibernate?

A depth tutorial about hibernate orphan removal true here.

Write an example of Named and Native query in Hibernate?

Why the entity should have a default constructor?

Hibernate EHCache vs Spring EhCache.

What are the exceptions you have faced in hibernate?

 

That’s all about Hibernate Interview Questions And Answers.