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

Format Decimal Numbers using Strings Within Pattern

As mentioned in earlier posts, the java.text.DecimalFormat class is used to format decimal numbers via predefined patterns specified as String. Apart from the decimal separator,...

Convert List to Array Using Stream with Param

There is an overloaded version of the Stream.toArray method which can be used to return a result array that is of the same data...

Concatenate Strings Using String Joiner

Java 8 has added a new class called StringJoiner. This concatenates Strings using a delimiter as well as adds a prefix and suffix to...

Â

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

Convert List to Array Using Stream with Param

There is an overloaded version of the Stream.toArray method which can be used to return a result array that is of the same data...

Java Tutorial #6 – Jump Statements

Introduction The break statement is used to stop further execution. It can be used either in a loop or within a switch statement. Break Statement The break...

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...

CHECKOUT TUTORIALS

Java Tutorial #1 – Variables and Data Types

Table of Contents Introduction 1. Variables 2. Data Types Primitive Data Types Integer Data Types Decimal Data Types Character Data Types Boolean Data Types Reference...
- Advertisement -spot_img