What is Hibernate Framework?
Hibernate is an open-source object-relational mapping (ORM) based java persistence framework. It is an ORM mapping tool in java. Hibernate is designed with the need to reduce complexity while connecting a relational database through java. Hibernate framework is designed to map java objects to implement object-oriented programming in the relational database. This is how to hibernate connects to the relational database to execute queries:
- Hibernate connects directly with the specified database and uses hibernate query language (HQL) to execute queries and map query results to java objects.
- Hibernate uses properties set in Hibernate configuration XML file to map query results to java objects.
- The database connection is created using a session that helps in saving and fetching the persistent java object.
- The session is created using the Session factory interface. In an ideal case, there should be only one session factory per database.
Comparison of Hibernate and JDBC
Here is a comparison table showing the difference in hibernate and JDBC:
Hibernate | JDBC |
Hibernate contains concrete classes which provide boilerplate logic. | JDBC provides only interfaces and abstract classes. |
All exceptions thrown by hibernating are unchecked. | All classes in JDBC throw checked exceptions. |
It does not require more resource management and does it internally. | It requires more resource management like opening and closing of resources. |
Stores java objects directly. | It cannot store objects directly. |
Supports database independent queries. | Supports database-specific queries. |
Supports Caching. | It does not support caching. |
Support lazy loading. | It does not support lazy loading. |
Hibernate Framework Architecture
Hibernate follows the layered architecture and has the following layers:
- Java application layer
- Hibernate layer
- Backend API Layer
- Database Layer
Hibernate layer contains the following components which are as follows:
1. Hibernate Configuration Object
This is the first object one has to create to establish database connection using hibernate. It should be ideally created once, during application initialization. The configuration object provides the following:
- Database Connection: Database connection is established using one or more configuration files. The files are hibernated .properties and hibernate.cfg.xml.
- Mapping: This creates a mapping between java classes and relational database tables.
2. Session Factory
Configuration object created in step 1 is used to create a session factory object which makes hibernate configuration ready using the provided configuration file and make way for session object to be created. Since the session factory is a heavy object, it is usually created once during the starting phase of the application. There is a need for multiple session factory object in case connections to multiple databases needs to be established. Also, the session factory is a thread-safe object.
3. Session
The session object establishes a physical connection with the database. It is a lightweight object and should be created each time interaction with the database is required. If an object needs to be persisted or needs to be retrieved, it can only be done using the session object. Session object should be closed as soon as the required operation is completed because they do not thread-safe.
4. Transaction
It is an optional object and represents a unit of work done with the database. A transaction object ensures that either all operations must execute or none of them must execute. It is a single-threaded and short-lived object.
5. Query Object
This object uses structured query language (SQL) or Hibernate Query Language (HQL) to fetch data from the database and instantiate objects. A Query object can be used to limit output returned from the query, bind query parameters and execute the query.
Queries
Here we will execute some queries that will make things more clear. Let us consider an Entity Employee having class structured as:
Code:
package com.edubca.hibernatetest;
@Entity
@Table(name = "EMPLOYEE")
public class Employee implements Serializable
{
private static final long serialVersionUID = -1798070786993123455L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "empID")
private Integer empID;
@Column(name = "NAME")
private String empName;
@Column(name = "SALARY")
private Integer salary;
//Getters and setters
}
Hibernate requires an XML file called hibernate.cfg.xml that looks like:
Code:
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatetest</property>
<property name="hibernate.connection.password"> edubca</property>
<property name="hibernate.connection.username">edubcauser</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="com.edubca.hibernatetest.Employee"></mapping>
</session-factory>
</hibernate-configuration>
Below is the code to show how insertion and retrieval take place into the database using hibernate:
Code:
//Create Configuration object
Configuration con=new AnnotationConfiguration().configure(new File("hibernate.cgf.xml"));
// create session factory using configuration
SessionFactory fact=conf.buildSessionFactory();
//get session from session factory
Session session=fact.openSession();
//Instantiate and populate Employee entity object
Employee emp=new Employee();
emp.setempID(1);
emp.setempName("Yash");
emp.setSalary(40000);
Employee emp1=new Employee();
emp1.setempID(2);
emp1.setempName("Aman");
emp1.setSalary(42000);
//persist emp object
session.save(emp);
//persist emp1 object
session.save(emp1);
//retrieve data from database
Query query=session.createQuery("from Employee");
List<Employee> list= query.list();
For(Employee e : list){
System.out.println("Employee with ID " + e.getempID() + " has Name " + e.getempName() + " has salary " + e.getsalary());
}
Output:
An employee with ID 1 has Name Yash has a salary of 40000.
An employee with ID 2 has Name Aman has a salary of 42000.
Conclusion
In this article, we have covered hibernate in detail, about its architecture, comparison with JDBC and code examples. We also noted that hibernate provides a simple and efficient way to interact with the database.
Recommended Articles
This is a guide to the Hibernate Framework. Here we discuss the architecture, components, and comparison of hibernate and JDBC with code examples. You may also look at the following articles to learn more –