10X Sale
kh logo
All Courses

Introduction

Hibernate is an open-source object-relational mapping (ORM) tool for the Java programming language. It provides a framework for mapping an object-oriented domain model to a relational database. It helps developers to write code using plain Java objects and annotations to define the mapping between the Java objects and the relational database. Whether you’re preparing for a beginners' interview or appearing for advanced-level interview, our set of curated hibernate interview questions and answers will help you appear for the interview more confidently.

Hibernate Interview Questions and Answers
Intermediate

1. What are POJOs and what is their use?

POJO stands for Plain Old Java Object. Hibernate is based on the concept of taking values from Java class attributes and storing them in a database. Such classes whose objects are stored in a database are known as persistent classes. These classes have proper getter and setter methods for every property. These classes also have a default constructor. These classes should be non-final or have an interface with all the public methods declared. An ID is mandatory for each object of these classes as they will be mapped to the primary column of the table. Use of POJOs instead of simple java classes results in an efficient and well – constructed code. A simple example of a POJO class is as below:

public class Student{ 
private int id; 
private String firstName; 
private String lastName; 
private int age; 
public Employee(){} 
public Employee(String fname,String lname,int age){ 
this.firstName=fname; 
this.lastName=lname; 
this.age= age; 
} 
public int getId(){return id; } 
public void setId(int id ){ this.id = id;} 
public String getFirstName(){ return firstName;} 
public void setFirstName(String first_name){  
this.firstName=first_name; 
} 
public String getLastName(){ return lastName; } 
public void setLastName(String last_name){  
this.lastName=last_name; 
} 
public int getAge(){ return age; } 
public void setAge(int age ){ this.age= age; } 
} 

2. What are derived properties?

Derived properties are properties that are not mapped to any column of a database table. They are also known as calculated properties and are calculated at runtime. These properties are read-only in nature and can be defined using the @Formula annotation or by using the <formula> tag in the hbm.xml definition file. To use the @Formula annotation, we need to import org.hibernate.annotations.Formula package. 

Let us look at an example. 

@Entity 
@Table(name="EMPLOYEE") 
public class Employee implements java.io.Serializable { 
    @Id 
    @Column(name="ID") 
    private Integer id; 
    @Column(name="FIRST_NAME", length=50) 
    private String firstName; 
    @Column(name="LAST_NAME", length=50) 
    private String lastName; 
    @Column(name="MONTHLY_SALARY") 
    private float monthlySalary; 
    @Formula("MONTHLY_SALARY*12") 
        private float yearlySalary; 
    public Employee() { } 
    public Integer getId() { return id; } 
    public void setId(Integer id) { this.id = id; } 
    public String getFirstName() { return firstName; } 
    public void setFirstName(String firstName) {  
this.firstName = firstName;  
  } 
    public String getLastName() { return lastName; } 
    public void setLastName(String lastName) { this.lastName = lastName; } 
    public float getMonthlySalary() { return monthlySalary; } 
    public void setMonthlySalary(float monthlySalary) {  
this.monthlySalary = monthlySalary; 
    } 
    public float getYearlySalary() { return yearlySalary; } 
} 

In the above example, the @Formula annotation refers to the MONTHLY_SALARY column in the database table and not the monthlySalary property in the class. 

            The hbm mapping for the above class would be: 
<?xml version="1.0"?> 
<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
<class name="com.other.domain.entity.Employee" table="EMPLOYEE"> 
<id name="id" type="integer" access="property"unsaved-value="null"> 
<column name="ID"/> 
<generator class="native"/> 
</id> 
<property name="firstName" type="string" column="FIRST_NAME"/> 
<property name="lastName" type="string" column="LAST_NAME"/> 
<property name="monthlySalary" type="float" column="MONTHLY_SALARY"/> 
      <property name="yearlySalary" type="float" column="YEARLY_SALARY" 
formula="(SELECT (MONTHLYSALARY*12) from EMPLOYEE e where e.id = ID)"/> 
</class> 
</hibernate-mapping> 

3. How many types of collection are there in Hibernate? Explain Collection Mapping?

This is a frequently asked question in hibernate interview questions for freshers.

The Hibernate collections behave like HashMap, HashSet, TreeMap, TreeSet or ArrayList. Collection instances are like value types and are automatically persisted when referenced by a persistent object and deleted when unreferenced. There are five types of collections in Hibernate. They are: 

  1. Map  
  2. Array 
  3. List 
  4. Set 
  5. Bag

To map these collections, the type of collection must be declared from one of the following: 

  • java.util.List 
  • java.util.Set 
  • java.util.SortedSet 
  • java.util.Map 
  • java.util.SortedMap 
  • java.util.Collection 
  • or write the implementation of org.hibernate.usertype.UserCollectionType

The Hibernate mapping element used for mapping a collection depends upon the type of interface. The basic syntax for mapping is: 

<hibernate-mapping> 
<class name="<event.Class>" table="<TableName>"> 
          <id name="id" column="<ColumnName>"> 
                   <generator class="native"/> 
          </id> 
         <property name="<property>" type="<type>" column="<ColumnName>"/> 
         <property name="<property>"/> 
        <set name = “<name of set>”> 
<key column=“<column name>” not-null= “true”/> 
                       <one-to-many class=“<associated class>”/> 
        </set> 
</class> 
</hibernate-mapping> 

The <set> can be replaced with map, list etc. There are different associations for mapping the class with the corresponding table. The types of associations are as below: 

  1. one-to-many 
  2. one-to-one 
  3. many-to-one 
  4. many-to-many 

When using a map for mapping, a map-key has to be provided along with the key column.  

<map name="developmentLanguages" table="tdevelopmentlanguage" cascade="all"> 
         <key column="developer_id" not-null="true"></key> 
         <map-key type="string" column="shortname"></map-key> 
        <element column="name" type="string"></element> 
</map> 

4. What is Hibernate Proxy and how does it impact loading?

A proxy is defined as a function which acts as a substitute to another function. When a load() method is called on session, a proxy is returned and this proxy contains the actual method to load the data. 

The session.load() method creates an uninitialized proxy object for our desired entity class. The proxy implementation delegates all property methods except for the @id to the session which will in turn populate the instance. When an entity method is called, the entity is loaded and the proxy becomes an initialized proxy object. 

Let us understand this with an example. Let us assume that there is an entity called Student. Let us also assume that initially, this entity has no connection or relation with any other tables except the Student table. When the session.load() method is called to instantiate the Student, 

Student dia = session.load(Student.class, newLong(1)); 

Hibernate will create an uninitialized proxy for this entity with the id we have assigned it and will contain no other property as we have not yet communicated with the database. However, when a method is called on dia, 

String firstName = dia.getFirstName(); 

Hibernate will fire a query to the database for information on the student with primary key 1 and populates the object dia with the properties from the corresponding row. If the row is not found, Hibernate throws an ObjectNotFoundException 

5. Explain Session?

The session object is used to connect with a database. It is light-weight and is instantiated every time a database connection is required. Sessions are not thread safe and so should not be kept open for long. These objects should be created as needed and should be destroyed if not in use. Sessions hold a first-level cache of data. The org.hibernate.Session interface provides methods to insert, update and delete the object. It also provides factory methods for Transaction, Query and Criteria. 

The main functionality of Session objects is to provide create, read and delete operations to the instances of the mapped entity classes. The instances may be in one of the following states at any given point. 

  1. Transient: When an instance of a persistent class is not associated with a session, has no database representation and has no identifier value, such an instance is considered to be in the transient state 
  2. Persistent: An instance becomes persistent when it is associated with a session, has database representation and has an identifier value   
  3. Detached: An instance is detached, once the Hibernate session is closed. 

A session instance becomes serializable if its persistent class or classes is/are serialised. If a session throws an error, the transaction has to be rolled back and the session instance has to be deleted. 

Want to Know More?
+91

By Signing up, you agree to ourTerms & Conditionsand ourPrivacy and Policy

Description

Hibernate is a Java framework. It is a lightweight, open-source Object Relational Mapping tool (ORM). It is used to generate persistence logic, that is, it is used to store and process data for long use. Here, we have brought together the most frequently asked Hibernate interview questions to familiarize you with the skills and knowledge required to succeed in your next Hibernate job interview. If you want to learn more about Hibernate, enroll in our Hibernate Course and learn more about it.

Here are some of the world’s most popular and top-rated organizations that are using Hibernate:

  1. Bodybuilding.com
  2. StyleShare Inc.
  3. Peewah
  4. Zolkin
  5. Zendy Health, etc.

Hibernate integrates with Java, AnyChart, and TimescaleDB. If you are looking to build your career in the field of Hibernate, then begin by choosing a Hibernate Training program and start a career as a Java Architect-Hibernate, Java Developer-Hibernate, Java Lead Hibernate, etc.

Taking up a training program will help you attain various skills, which will be an advantage. A Java Developer with Hibernate skills has an average pay of US$78,195 per year, with experienced Java Developers with Hibernate skills earning as high as US$108,000. If you want to learn vastly about computer programming training courses, you can join KnowledgeHut to upskill your career today.

These Hibernate interview questions and answers have been designed in such a manner that they will get you familiarized with the nature of questions that you might face during your interview and will help you to crack Hibernate Interview easily & acquire your dream career as a Java Architect-Hibernate, Java Developer-Hibernate, Java Lead-Hibernate, etc. These highly rated Hibernate interview questions will surely boost your confidence to face an interview and prepare you to answer your interviewer’s questions best. The experts suggest these interview questions on Hibernate.

Wish you all the luck and confidence!

Recommended Courses

Learners Enrolled For
CTA
Got more questions? We've got answers.
Book Your Free Counselling Session Today.