Getting Started With Hibernate

A brief introduction of hibernate

Table of Contents

Introduction

Hibernate is a framework which allows you to access database tables from Java code. Before Hibernate came into existence, JDBC was widely used. JDBC is an API to access a relational database from a java program. JDBC basically allows you to execute SQL statements from Java code, so any SQL statement which you can run on a database directly, you can run it from your Java code via JDBC.

How JDBC works

JDBC requires writing code for connecting to the database, executing an SQL query and obtaining the results. The following code demonstrates this:

Class.forName("com.mysql.jdbc.Driver"); //Register JDBC Driver
Connection conn = DriverManager.getConnection(url, username, password); //Open a //connection
Statement stmt = conn.createStatement(); //create a statement
ResultSet rs = stmt.executeQuery("Select * from person");// Execute a query
Person person = new Person();
while(rs.next()){ //iterate through the resultset
      String name = rs.getString("name"); 
	person.setName(name);
       //more code for other fields
 }
 rs.close();
 stmt.close();
 conn.close();

This code queries a table called Person via JDBC. So, as you can see, you need to write a lot of code in order to query a table. The JDBC code needs you to register the JDBC driver, open a database connection, create a statement, execute the query, iterate through the results, map each field to the fields in an object and finally close the Resultset, Statement and Connection objects.

Problems with JDBC

This code written via JDBC is not only bulky and difficult to read, but it has several other disadvantages too. It uses SQL directly in the code. So, if you use database specific SQL syntax, it becomes tedious to migrate to a different database. Secondly, it has a lot of boilerplate code like creating connections/statements and closing them. Also, it is not object oriented and it is hard to map database tables to objects in the code. Finally, it is not extensible. For example, if you want to make a change to a database table like adding or removing a column, the code needs to be modified in order for the changes to work.

What is Hibernate

Hibernate is an ORM tool. ORM is a programming technique that allows you to map Java objects to database tables and vice versa. Hibernate is one such ORM tool available for Java. There are other ORM tools like TopLink, Spring DAO, etc.

Why Hibernate

Hibernate or any ORM tool for that matter does away with most of the boilerplate stuff that is required by JDBC.  The code that you need to write is more object oriented and directly maps the Java code with database tables.

The above code can be rewritten using Hibernate as follows:

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Person person = session.load(Person.class, 2);
tx.commit();
session.close();
HibernateUtil.closeSessionFactory();

So, if you look at this code, it’s much cleaner. There are no SQL statements since your objects are mapped to tables.

How Hibernate works

In order to use Hibernate in your application you need to do the following:

  • Create a configuration file that has details about the database connection, URL, etc
  • Create POJO classes corresponding to the database tables. So, each table needs to have a class with fields that correspond to the columns in the table.
  • Provide mapping information either via an XML file or annotations. This mapping information specifies how each class maps to the corresponding database table
  • Invoke methods on the Hibernate session interface to perform database operations

Hibernate uses the information in the configuration file to establish a database connection. It then uses the mapping information and maps the POJO class to the corresponding database table. When you invoke code to perform database operations, Hibernate automatically converts your code into SQL statements.  So, compared to JDBC, Hibernate provides a much cleaner and easy to use approach.

Hibernate Integration with JPA

JPA stands for Java Persistence API. Over time, just like Hibernate several ORM frameworks were developed. Each framework had its proprietary code. So, if developers wanted to switch from one framework to another, it was not possible. To address this issue, Java introduced the JPA specification. JPA was developed as a standard way to access relational tables from Java code. JPA is just a specification, it is not an implementation. So, if the proprietary frameworks implemented the JPA specification, it was possible to switch from one framework to the other.

Over time, Hibernate was made JPA compatible, that is, it was made to implement the JPA specification. So, in addition to its own proprietary methods, Hibernate also supports JPA methods. So, if your application code uses the JPA specific methods in Hibernate, then it becomes easy to replace Hibernate with some other JPA implementation.

Conclusion

Hibernate was developed to overcome the shortcomings of the JDBC framework.  Compared to JDBC, it provides a more object oriented and cleaner approach to access database tables from Java code.  In addition, Hibernate is also a JPA provider and implements the JPA specification.

Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

RELATED POSTS

Convert List to Array Using ToArray With Param

There is an overloaded version of the toArray method. This accepts an array as a parameter and returns a result array that is of the same...

How To Sort List in Java

Introduction A List is an interface in the Java collection framework. It can be used to store objects. Programmers often encounter scenarios where they need...

How To Create Singleton Class in Java

Design patterns Overview Design patterns are basically solutions to programming problems that developers normally encounter during software development. Design patterns were first documented by four...

Â

RECENT 'HOW-TO'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string with a function or variable. It does not...

SIMILAR ON CODEX

FEATURED PROJECTS

Windows JDK Manager (win-jdk-Manager)

ADjo LABS PROJECT : Simple and lightweight desktop utility with Interactive cmd Interface for easy view, re-point and switching between JAVA versions on windows. Demonstrating the capability...

MORE IN THIS CATEGORY

How To Create Maven Project Using Command Line

Maven project can be easily created using built-in plugins from the popular IDEs such as Eclipse and IntelliJ IDEA. However, in scenarios where you...

What is In-Proc and Out-Proc (COM) ?

The terms 'In-Proc' and 'Out-Proc' are to describe the kind of implementation of COM Servers. Before we begin, for those who are not quite...

Convert List to Array Using ToArray Without Param

Java provides a toArray method on the 'List' interface. This can be used to convert a 'List' to an array. Since there are are...

CHECKOUT TUTORIALS

VBS Part 2 – Fundamentals and Concepts

Having gone through the Introductory part, it is time to look at some crucial fundamentals and concepts. This article is to refresh some of...
- Advertisement -spot_img