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>

What are the Collection types in Hibernate?

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

What is HibernateTemplate?

The spring framework provides HibernateTemplate(org.springframework.orm.hibernate.HibernateTemplate) which is kind of helper class and provides following benefits.

- HibernateTemplate class simplifies interaction with Hibernate session.
- Common functions are simplified to single method calls.
- Sessions are automatically closed.
- Exception are automatically caught and converted to runtime exceptions.

What is the difference between load() and get() method?

load() :

- Use load() method only when you are sure that object you want to read already exists.
- If unique Id of an object does not exists in database then load() method will throw an exception.
- load() method return proxy object default and database won't be hit until the proxy is first invoked.

get() :

- Use get() method when you are not sure obout the object existance in the database.
- If object does not exists in the database, the get() method will return null.
- get() method will hit database immediately.

What is lazy fetching in Hibernate?

In Hibernate Lazy fetching is associated with child objects loading for its parents. Through Hibernate mapping file (.hbm.xml) you can specified the selection of loading child objects. By default Hibernate does not load child objects. Lazy=true means not to load the child objects.

What is the difference between merge and update method?

Use update() method when you are sure that session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

How do you define sequence generated primary key in hibernate?

Using <generator> tag.
- Example :
<id column="CUST_ID" name="id" type="java.lang.Long">
<generator class="sequence">
<param name="table">SEQUENCE_NAME</param>
<generator>
</id>

What are the different types of caches in Hibernate?

Hibernate uses two different type of caches for objects: first-level cache and second-level cache. First level of cache is associated with Session object, while second-level of cache is associated with the SessionFactory object. By default, Hibernate uses first-level of cache on a per-transaction basis. Hibernate mainly use this cache to reduce the number of SQL queries it needs to generate within a given transaction.

What do you mean by Named – SQL query?

- Named SQL queries are defined in the mapping xml document and called wherever required.
- Example :
<sql-query name = "empdetails">
<return alias="emp" class="com.test.Employee"/>
SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>
Invoke Named Query :
List people = session.getNamedQuery("empdetails")
.setString("Deepak", name)
.setMaxResults(50)
.list();

How does Hibernate useful in mapping object and its relations?

- Hibernate is a framework for Java that is used to map the object and its relations.
- It is used to build persistent objects using the terminologies of JAVA.
- It uses the following properties to perform the function of mapping :
1. Association : Where the one object can be associated with another object of the same or different class.
2. Inheritance : It is a property of inheriting the properties and features of the parent class.
3. Polymorphism : It is a feature that allows more than one data type to be handled by a single function.
4. Composition : It is used to combine the simple data types into complex data types.

What is the function performed by code generator in Hibernate?

Code generator is a framework that allow simple and easy mapping of objects using pre-defined tags. It follows Model driven architecture which uses models of the objects separately and link them with each other. Code generator adds attributes to the source code. I uses the java-doc tags to generate the hibernate mapping. It is also used to generate the database definition language from the source code to map the objects correctly. It allows easy mapping of objects from an existing database and allow it to be connected to some different database model as well.

What is the need of hibernate tools when ORM tools can be used?

The use of hibernate tools is to allow the programmer to code efficiently and saves them from being involved with the SQL code directly. It is used to increase the productivity of the work and uses high level object oriented APIs to increase the efficiency and performance of the work. It allows the programming to be more objects oriented and the code in Java has to be written less. It also save programmers time to write the SQL code as there is no need to write the SQL code in it. These tools provide very good caching system that keeps all the files and they provide it when it is required. It allows easy maintenance of the overall system and the code that is being written in it.

What are the tags that are importantly used in Hibernate configuration file?

Hibernate configuration file is the most important file. The configuration file consists of many tags and they are as follows :

DTD : This is also called as Document type definition and is written as :
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD/EN”
“ http://hibernate.sourceforge.net/hibernate-configuration-3.0 dtd”>
JDBC connection configuration tag : JDBC stands for Java Database connectivity tags that gives the driver name and the database related information and represented as :
<property name= “hibernate connection.driver_class”>org.hsqldb.jdbcDriver</property>
SQL variant : It specifies the SQL statement to generate the particular property in the database. It is given as :
<property name= “dialect”>org.hibernate.dialect.HSQLDialect</property>
Conn pool : This tag is very important to set the size of the conn pool for the correct connection. It is given as :
<property name= “hibernate.connection.pool_size”>10</property>
Property to generate the database schema : This property tag generates the database schema automatically. It is given as :
<property name= “hibernate.hbm2ddl.auto”>create-drop</property>
Mapping files : These files are important to map the resources of the same or different objects. It is given as :
<mapping resource= “Event.hbm.xml”>

What is the role played by Session interface in Hibernate?

Session interface is the primary interface used by Hibernate. It is the important interface for the applications that uses single thread, and a short lived object representing a conversation between application and the objects that are stored. This object allows creating query objects that can be used to call persistent objects from the database. This interface allows the wrapping of JDBC connection and keeps the transactions at one place. It holds the persistent objects in the cache for easy navigation and to increase the performance of the overall system. The interface is represented as :
Session session = sessionFactory.openSession();

What is the role played by SessionFactory interface in Hibernate?

The session instance is being obtained by the application from SessionFactory. It keeps the session instances at one place for easy access and dynamic allocation of the resources. There is always a single SessionFactory created for the complete application. This is created during the application initialization. It creates the cache that is used to generate the SQL statements and metadata information about the mapping of the Hibernate functions that gets used in runtime. It holds the data that has been cached and then read into it. It focuses on reusability of the work and the functions that are stored in the SessionFactory. This is represented as :
SessionFactory sessionFactory = configuration.buildSessionFactory();

What is the process of communication between Hibernate with RDBMS?

To create the communication between the Hibernate and RDBMS there are some steps that are involved in the process. These are as follows :

- To create the communication first loading of the Hibernate configuration file takes place. When this file is loaded then a configuration object gets created. This object loads the .hbm files used to map the objects automatically.
- A session gets created by taking the interface from the SessionFactory from the configuration object.
- A HQL query is being creation after taking the session from the session factory and starting the session for the user.
- In the end an execution of the query gets listed that contain the Java Objects of the file. This allows the communication being done between different objects of Hibernate and RDBMS.

What is the purpose of HQL in communication between Hibernate and RDBMS?

HQL stands for Hibernate Query language and is used to set the communication between the Hibernate and RDBMS. It is a powerful language that uses flexible mechanism for query, store, and update to take the objects from the database. It uses the objects for making a connection between the Hibernate and the database. It is an extension to the SQL that uses an Object oriented paradigm to communicate and retrieve the data from the database. It uses inheritance, polymorphism and abstraction features to handle the request and respond to the queries coming from the user.

Write the code that maps the Java Object with the database tables?

To map the Java Object with the database tables there is a need to write the code of Java domain objects. Java domain objects use the methods setter and getter to retrieve the Java objects and maps it accordingly. The file that is used to be written to map java class or object to the database table is hbm.xml. This file also maps the database columns to Java class variables. The code that is being written to perform the above mentioned operation is given below :

<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>

What is the purpose of using HibernateTemplate?

HibernateTemplate is a spring template that is used as a class to simplify the interaction with the Hibernate Session. HibernatTemplate includes simplified single method calls that are used to close the sessions automatically. It includes the exception handler that catches the exception automatically and converted it in runtime. There are classes used in Hibernate that provides different methods for query and to retrieve the data from the database. The helper class that is provided is org.springframework.orm.hibernate. HibernatTemplat is used to check and convert the HibernateExceptions into unchecked DataAccessExceptions.

How components are used in Hibernate?

Components allow the object to be saved as a value and not as a reference. It is used to be saved directly without the need to declare the properties of the interfaces or identifier in the application. Components in Hibernate define the empty constructor in which the references that are shared are not supported. The components class will be defined as :
public class hello
{
   private String a;
   private int b;
   private string c;
   //write your own code here
}

Write a code to do the component mapping in Hibernate.

To do the component mapping there is a requirement for two component classes that has to be made to establish the connection between them. So, the first component class will be like this :
public class hello
{
   private String a;
   private int b;
   private string c;
   //write your own code here
}
Another class will be written like this :
public class comp
{
   // properties
   private String a;
   //write get and set methods
   //write your own code here
}
The class that will be used to map the two components are written as :
<class name= “no.uio.inf.model.table=hello”>
<!—other properties-->
<component name= “comp”>
<property name = “a”/>
<property name = “b”/>
<property name = “c”/>
</component>
</class>

Why Hibernate is preferred over JDBC?

The preference of Hibernate is more due to the transparency it provides to the programmer for writing their code. It doesn’t allow the programmer to write explicit code to map the database tables to the application objects that are used during the interaction with RDBMS. It provides an advanced ORM solution to map the Java class files to the database tables for easy access and retrieval of the data. Hibernate uses Hibernate Query Language that is independent of the type of database used. It allows polymorphic queries to be retrieved and selects the way to perform the database manipulation tasks. Hibernate allow the storing of large amount of data in small files that can be easily accessed and the performance can be faster. It also provides the actually mapping to be performed between the tables and objects in the XML files.

What is the use of Hibernate proxy in Hibernate?

The proxies are easy to create and it is created dynamically by sub-classing the objects at runtime. This sub-class consists of all the parent methods and allows easy accessing of them. The proxy allows the loading of this object in real time from the database and calls the methods from there. Proxy is used as a mechanism in Hibernate allowing breaking of the objects in the database in smaller parts that can easily be accessed and use the memory efficiently. It is easy for a class to be mapped to a proxy than to a table. When there is a call load on a sessioin then the value that is returned is the proxy. The proxy consists of the methods to load the data. The sample code to call the proxy is given as :
<class name="a" proxy="com.ch01.a">
</class>

What is the difference between managed and non-managed environment in Hibernate?

It is important to configure the Hibernate file properly so that it will be easy to manage and access the database. The difference that has to be known for the Hibernate is between Managed and non-managed environment :

- Managed environment allows the pooled resources of database connections to be loaded on run time. It also allows the transaction to be taken place smoothly in the specified boundaries, whereas non-managed environment provides the basic concurrency management using the method of thread pooling.
- Managed environment allows automatic transaction of the resources, whereas non-managed environment doesn’t provide any automatic transaction of the resources.
- Managed environment provides automatic management of security infrastructure, whereas non-managed environment doesn’t provide this.

What are the different types of interfaces present in Hibernate?

Hibernate consists of many interfaces to keep everything dynamic and up-to-date. The interfaces are as follows :

- Configuration interface: this interface includes the configuration object that is used to configure and bootstrap the Hibernate applications. It allows the need to map the documents and other related properties. It also allows the creation of the SessionFactory.

- Transaction interface: is an optional interface API that is used to manage the transaction of the infrastructure code. It allows the portability of the application that is executed in different environments and containers.

- Query and Criteria interfaces: it allows the performance of different queries that is against the database and it controls the execution of the queries as well. The queries are written either in HQL or SQL that depends on the database being used.

Why are callback interfaces useful in Hibernate?

Callback interfaces are useful as it allows the application to receive important notification about the objects that are in execution phase. It includes the objects that are loaded, saved or deleted from the Hibernate. Callback interfaces are very important to implement the general functionality like audit records, etc. It sends a notification when any object even occurs. It allows the programmer to get the error information or exception handling can be done in a better way to notify the user on run time in case of any problem in the programming code.

What is the importance of Lifecycle and validatable interface in Hibernate?

Lifecycle and validatable interface allows the object that is persistent to react to certain events that occurs during their own persistence lifecycle. The lifecycle is managed by the CRUD operations which handles the object lifecycle as well. Hibernate uses ORM solution that are similar in functionality of the callback interface. It allows easy portable code for the transaction to be saved and persistent classes and objects can be validated and sent over for implementation and use.

What are the different types of extension interface that is present in Hibernate?

Extension interface allows easy implementation of other interfaces according to the user’s requirements. It allows different functionality to be provided when the built in functionality is not sufficient for the users. The extensions that are provided for the use is as follows :

ProxyFactory interface : It is used to create proxies to help in maintaining the mapping of the objects.
ConnectionProvider interface : It is used to provide the JDBC connection management for easy mapping of the object with the database.
TransactionFactory interface : It is used to provide the transaction management.
TransactionManagementLookup interface : It is used to provide the way to look up the transactions that is being managed by transaction management interface.
Cahce interface : It is used to provide the caching techniques and strategies for the objects to speed up the process.
IdentifierGenerator interface : It is used to provide a way to generate the keys like primary key to uniquely identify the objects.
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