Hibernate interview questions and answers - Freshers & Experienced

What is Hibernate?

- Hibernate is an ORM (Object Relational Mapping) and persistent framework.
- The framework helps to map plain java object to relational database table using xml configuration file.
- The framework helps to perform following things.
1. Perform basic CURD operations.
2. Write queries referring to java classes (HQL queries).
3. Facilities to specify metadata.
4. Dirty checking, lazy association fetching.

Why hibernate and how does it help in the programming?

The main advantage of Hibernate (ORM) framework is that it shields developer to write a messy SQL. Apart from that ORM provides following benefits.

1. Improve Productivity of the developer by providing high level object oriented API (e.g. API for easily maintaining the connection to data base, mapping java classes to relational database tables), less java code to write, helps to avoid writing SQL query.
2. Improved performance by providing sophisticated caching, lazy loading and eager loading features.
3. Provide portability, the framework helps to generate database specific SQL for you.

How will you configure Hibernate?

- To configure hibernate, you need hibernate.cfg.xml or hibernate.properties file and *.hbm.xml files, all these files are used by configuration class to create sessionFactory, which in turn creates the session instances.
- Session instances are the primary interface for persistence services.
- The hibernate.cfg.xml or hibernate.properties files are used to configure the hibernate service (database connection driver class, database connection URL, connection username, connection password, dialect, mapping resources etc.).
- The *hbm.xml files are used for mapping persistent objects to relational database.
- From Java 5 onwards you can configure and map persistent objects through annotations.

Which settings will be loaded if both hibernate.properties and hibernat.cf.xml files are present in the classpath?

If both hibernate.properties and hibernate.cfg.xml files are present in the classpath then hibernate.cfg.xml file will override the settings found in hibernate.properties. So please make sure that your project should include either hibernate.properties or hibernate.cfg.xml file.

What are the Core interfaces of Hibernate framework?

There are five core interfaces being used extensively in every Hibernate application. Using these interfaces you can store or retrieve any persistent objects and also control transactions.

1. Session interface
2. SessionFactory interface
3. Configuration interface
4. Transaction interface
5. Query and Criteria interfaces

What is the role of Session interface in Hibernate?

The session interface is the primary interface used in Hibernate Application.
- It is a single threaded sort-lived object and represents conversation between application and the persistent store.
- It helps to create query objects to retrieve persistent objects.
- You can get the session object from session factory :
Session session = sessionFactory.openSession();
- Session Interface role :
1. Wraps a JDBC connection.
2. Factory for Transaction.
3. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier.

What is the role of SessionFactory?

The application obtains session object from SessionFactory interface. Typically there should be only one sessionFacory for whole application and is loaded during application initialization. The SessionFactory caches generate SQL Statement and other mapping metadata that Hibernate use at runtime. It also hold cached data that has been read in one unit of work and can be reused in a future unit of work.
You can get the instance of SessionFactory by the configuration object as below :
SessionFactory sessionFactory = configuration.buildSessionFactory();

How do you implement one to one relationship in Hibernate with XML mapping?

- For example you have table emp(employee table) and emp_detail(employee details) and assuming there is a one to one relationship between them. For the above tables you have to create corresponding POJO classes and hbm.xml files.
- So for emp table the java class is Employee.java with property empId and xml file is emp.hbm.xml.
- And for emp_details the java class is EmployeeDetail.java (properties are name, address etc.) and xml file is empdetail.hbm.xml.
- So the final code will look like as below :
package com.test.onetoone.mapping
public class Employee implements java.io.Serializable
{
   private Integer empId;
   private EmployeeDetail empDetail;
}
package com.test.onetoone.mapping
public class EmployeeDetail implements java.io.Serializable
{
   private Integer empId;
   private Employee emp;
   private String name;
   private String address;
}
----- emp.hbm.xml ----
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.test.onetoone.mapping.Employee" table="emp">
<id name="empId" type="java.lang.Integer">
<column name="EMP_ID" />
<generator class="identity" />
</id>
<one-to-one name="empDetail" class="com.test.onetoone.mapping.EmployeeDetail"
cascade="save-update"></one-to-one>
</class>
</hibernate-mapping>

***********************empdetails.hbm.xml*******************

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.test.onetoone.mapping.EmployeeDetail" table="emp_detail"
catalog="mkyongdb">
<id name="stockId" type="java.lang.Integer">
<column name="EMP_ID" />
<generator class="foreign">
<param name="property">emp</param>
</generator>
</id>
<one-to-one name="emp" class="com.test.onetoone.mapping.Employee"
constrained="true"></one-to-one>
<property name="name" type="string">
<column name="EMP_NAME" length="100" not-null="true" />
</property>
<property name="address" type="string">
<column name="EMP_ADDR" not-null="true" />
</property>
</class>
</hibernate-mapping>

How do you implement one to one relationship in Hibernate with java annotation?

Taking the same Employee and Employee Details example of the above question.
Employee.java
package com.test.onetoone.mapping
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "emp")
public class Employee implements java.io.Serializable
{
   private Integer empId;
   private EmployeeDetail empDetail;
   public Employee(){}
   @Id
   @GeneratedValue(strategy = IDENTITY)
   @Column(name = "EMP_ID", unique = true, nullable = false)
   public Integer getEmpId()
   {
       return this.empId;
   }
   public void setEmpId(Integer empId)
   {
       this.empId = empId;
   }
   @OneToOne(fetch = FetchType.LAZY, mappedBy = "emp", cascade = CascadeType.ALL)
   public EmployeeDetail getEmpDetail()
   {
       return this.empDetail;
   }
   public void setEmpDetail(EmployeeDetail empDetail)
   {
       this.empDetail = empDetail;
   }
}
File: EmployeeDetail.java
package com.test.onetoone.mapping
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@Entity
@Table(name = "emp_detail")
public class EmployeeDetail implements java.io.Serializable
{
   private Integer empId;
   private Employee emp;
   private String name;
   private String address;
   public EmployeeDetail() {}
   public EmployeeDetail(Employee emp, String name, String address)
   {
       this.emp = emp;
       this.name = name;
       this.address = address;
   }
   @GenericGenerator(name = "generator", strategy = "foreign",
   parameters = @Parameter(name = "property", value = "emp"))
   @Id
   @GeneratedValue(generator = "generator")
   @Column(name = "EMP_ID", unique = true, nullable = false)
   public Integer getEmpId()
   {
       return this.empId;
   }
   public void setEmpId(Integer empId)
   {
       this.empId = empId;
   }
   @OneToOne(fetch = FetchType.LAZY)
   @PrimaryKeyJoinColumn
   public Employee getEmp()
   {
       return this.emp;
   }
   public void setEmp(Employee emp)
   {
       this.emp = emp;
   }
   @Column(name = "ADDRESS", nullable = false, length = 400)
   public String getAddress()
   {
       return this.address;
   }
   public void setAddress(String address)
   {
       this.address = address;
   }
   @Column(name = "EMP_NAME", nullable = false)
   public String getName()
   {
       return this.name;
   }
   public void setName(String name)
   {
       this.name = name;
   }
}
3. Hibernate Configuration File
- Puts annotated classes Employee.java and EmployeeDetail.java in your Hibernate configuration file, and also MySQL connection details.
File : hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mytestdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="com.test.onetoone.mapping.Employee" />
<mapping class="com.test.onetoone.mapping.EmployeeDetail" />
</session-factory>
</hibernate-configuration>

How do you implement one to many relationships in Hibernate?

- For one to many relationships we can consider the example Author and Books (i.e. one Author can have written many books).
- Below code will help you to understand how you can implement one to many relationship in hibernate.

File: Author.java
package com.test.one.to.many;
java.util.Set;
public class Author implements java.io.Serializable
{
   private Integer authorId;
   private String authorName;
   private Set books;
   // getter and setter
}
File: Book.java
package com.test.one.to.many;
public class Book implements java.io.Serializable
{
   private Author author;
   private Integer bookId;
   private String bookName;
   // getter and setter
}
File: Author.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.test.one.to.many.Author" table="author">
<id name="authorId" type="java.lang.Integer">
<column name="AUTHOR_ID" />
<generator class="identity" />
</id>
<property name="authorName" type="string">
<column name="AUTHOR_NAME" length="100" not-null="true" unique="true" />
</property>
<set name="books" table="book" inverse="true" lazy="true" fetch="select">
<key>
<column name="AUTHOR_ID" not-null="true" />
</key>
<one-to-many class="com.test.one.to.many.Book" />
</set>
</class>
</hibernate-mapping>
File: Book.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.test.one.to.many.Book" table="book">
<id name="bookId" type="java.lang.Integer">
<column name="BOOK_ID" />
<generator class="identity" />
</id>
<many-to-one name="author" class="com.test.one.to.many.Author" fetch="select">
<column name="AUTHOR_ID" not-null="true" />
</many-to-one>
<property name="bookName" type="string">
<column name="BOOK_NAME" />
</property>
</class>
</hibernate-mapping>
File: hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mytestdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="com/test/one/to/many/Author.hbm.xml" />
<mapping resource="com/test/one/to/many/Book.hbm.xml" />
</session-factory>
</hibernate-configuration>

How to implement one to many relationships with Annotation?

- You can implement one to many relationship with the help Annotation also.
- Below code will help you to understand the one to many relationship with java Annotation.

File : Author.java
package com.test.one.to.many;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "Author")
public class Author implements java.io.Serializable
{
   private Integer authorId;
   private String authorName;
   private Set<Book> books;
   // getter and setter

   public Author() {}
   @Id
   @GeneratedValue(strategy = IDENTITY)
   @Column(name = "AUTHOR_ID", unique = true, nullable = false)
   public Integer getAuthorId()
   {
       return this.authorId;
   }

   public void setAuthorId(Integer authorId)
   {
       this.authorId = authorId;
   }

   @Column(name = "AUTHOR_NAME", nullable = false, length = 100)
   public String getAuthorName()
   {
       return this.authorName;
   }
   public void setAuthorName(String authorName)
   {
       this.authorName = authorName;
   }
   @OneToMany(fetch = FetchType.LAZY, mappedBy = "author")
   public Set<Book> getBooks()
   {
       return this.books;
   }
   public void setBooks(Set<Book> books)
   {
       this.books = books;
   }
}
File : Book.java
package com.test.one.to.many;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "book")
public class Book implements java.io.Serializable
{
   private Author author;
   private Integer bookId;
   private String bookName;
   public Book() {}
   @Id
   @GeneratedValue(strategy = IDENTITY)
   @Column(name = "BOOK_ID", unique = true, nullable = false)
   public Integer getBookId()
   {
       return this.bookId;
   }
   public void setBookId(Integer bookId)
   {
       this.bookId = bookId;
   }
   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name = "AUTHOR_ID", nullable = false)
   public Author getAuthor()
   {
       return this.auther;
   }
    public void setAuther(Author author)
   {
       this.auther = auther;
   }
   @Column(name = "BOOK_NAME", length = 400, nulaable=false)
   public Float getBookName()
   {
       return this.bookName;
   }
   public void setBookName(String bookName)
   {
       this.bookName = bookName;
   }
}
3. Hibernate Configuration File

- Puts annotated classes Author.java and Book.java in hibernate.cfg.xml like this :
File : hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mytestdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="com.test.one.to.many.Author" />
<mapping class="com.test.one.to.many.Book" />
</session-factory>
</hibernate-configuration>

How will you integrate Hibernate with spring framework?

- To integrate hibernate with spring framework, the hibernate configuration will go in spring configuration file.
- The configuration file will look like as below :
<beans>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties"></bean>
<!—jdbc.properties database related properties -?

<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}"></bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

<bean id="employeeDAO" class="com.test.dao.EmployeeDaoImpl"></bean>
<bean id="employeeManager" class="com.test.service.EmployeeManagerImpl"></bean>

<tx:annotation-driven />

<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
1 2 3

Hibernate - What is ORM?
What is ORM? - Object Relational Model is a programming technique.....
Hibernate - What is Hibernate?
What is Hibernate? - Hibernate is an ORM tool. Hibernate is a solution for object-relational mapping...
Hibernate - Why do you need ORM tool like Hibernate?
Why do you need ORM tool like Hibernate? - Hibernate is open source ORM tool. Hibernate reduces the time to perform database operations...
Post your comment
Discussion Board
Hibernate
Questions are really gr!
Shailesh 03-5-2014