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 Stream without Param

Java 8 has added the Stream API that helps to easily perform bulk operations on Collections. A new method called stream() has been added...

Convert String to Date Using java.util.Calendar

The java.util.Calendar class also encapsulates a date. The Calendar class has some more features than the java.util.Date class. It provides the ability to extract...

Format Decimal Numbers Using Pattern

The java.text.DecimalFormat class is used to format numbers using a user specified formatting. This concrete subclass of NumberFormat, allows formatting decimal numbers via predefined...

Â

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

SEPA Bulk File Generator and Validator

ADjo LABS PROJECT: SEPA Bulk File Generator and Validator. Supported File Types PAIN008, PAIN001, PACS003 and PACS008. Tested for supporting PAIN.008.001.001 and PAIN.008.001.002 (version 1&2). The XML...

MORE IN THIS CATEGORY

Remove Duplicates from List Using LinkedHashSet

Another implementation of the Set interface is LinkedHashSet. LinkedHashSet maintains the order of elements and helps to overcome the HashSet limitation. The following code...

How To Convert String To Date in Java

Introduction There are often scenarios in programming, where you will need to convert a date in String format to an actual Date object. For example,...

VBS Part 1 – Introduction and Background

At the upfront, this theoretical article might look boring to most of us but still, it is advisable to know about our scripting friend...

CHECKOUT TUTORIALS

Finding Web Elements with Selenium

I'm going to explain in this tutorial about the usage of the findElement and findElements method of Selenium Webdriver on the Chrome web browser....
- Advertisement -spot_img