Benefits of Hibernate over JDBC

In this post, we will see the benefits of Hibernate over JDBC.

Database Independency.

Hibernate is a database-independent language. For example, supposes initially we have implemented MySql database and later if we want to use Oracle database then no need to change in java code.

For example, consider a hibernate program which saves the entity in the database and we are using Oracle database.

We have two java files and one configuration files.

package javatute;
@Table(name = "book")
public class Book {
	 @GeneratedValue(strategy = GenerationType.AUTO)
	 private int bookId;
	 private String bookName;


HibernateSaveEntityExample .java

public class HibernateSaveEntityExample {
	public static void main(String[] args) {

		Configuration cfg = new Configuration().configure();

		SessionFactory factory = cfg.buildSessionFactory();

		Session session = factory.openSession();

		Book book = new Book();


		book.setBookName("Rich Dad Poor Dad");

		Transaction transaction = session.beginTransaction();;

		System.out.println("Hello! Book object has been saved");





hibernate.cfg.xml. (Oracle database configuration).

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">SYSTEM</property>
<property name="connection.password">oracle</property>
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<property name="">create</property>
 <mapping class="onetomany.Book" />
 <mapping class="onetomany.Story" />


Now if someone wants to use My SQL or Postgres data they just need to change configuration file (hibernate.cfg.xml), no need to change in and


Reduced the boilerplate code.

Hibernate reduces the boilerplate code like creating the connection and loading the driver class etc. Hibernate provides a large number of API can be directly used to develop java application faster and easier.

Consider a scenario we want to save some record in database using JDBC and Hibernate. After saving the record we will retrieve those record using JDBC and Hibernate. Let’s see the sample code in both cases.

In Case of JDBC.

Saving the records.

public class JDBCExample {

	public static void main(String[] args) {

		Connection connection = null;
		Statement statement = null;
		try {

			connection = DriverManager.getConnection("databse details");
			statement = connection.createStatement();

			String sql1 = "INSERT INTO Book " + "VALUES (1, 'Godan')";

			String sql2 = "INSERT INTO Book " + "VALUES (2, 'Gaban')";

			String sql3 = "INSERT INTO Book " + "VALUES (3, 'Alchemist')";


			// Rietrive records from
			ResultSet results = statement.executeQuery("SELECT * FROM BOOK");

			while ( {
				int id = results.getInt("bookId");
				String name = results.getString("bookName");


		} catch (Exception e) {

		} finally {
			try {
			} catch (SQLException e) {




In the case of Hibernate.

public class HibernateExample {

	public static void main(String[] args) {

		Session session = null;
		SessionFactory factory = null;

		try {

			Configuration cfg = new Configuration().configure();

			factory = cfg.buildSessionFactory();

			session = factory.openSession();

			Book book = new Book();


			book.setBookName("Rich Dad Poor Dad");

			Transaction transaction = session.beginTransaction();;

			//Retrieving Book entity
			book = session.get(Book.class, book.getBookId());

		} catch (Exception e) {


		} finally {






Automatic table creation.

Hibernate provides the facility to create database table automatically. There is a property called which we need to configure in the configuration file and rest of thing hibernate will take care.

Possible value
1. validate – validate the table makes no changes in the database.
2. update – Update the existing table, if the table is not there create a new one.
3. create – first it will drop the existing table then it will create a new one.
4. create-drop – Drop the existing table when SessionFactory is closed explicitly.

See more details about hibernate.cfg.xml file here.

Hibernate support inheritance and association mapping.

This is the major benefit of Hibernate over JDBC. In JDBC there is no concept of inheritance or association mapping. In association mapping, it is easy to save and manage the entity. For example, when we save parent entity the child entity will save automatically.

Hibernate support XML as well well as annotation-based inheritance and association mapping.

See more about association mapping and inheritance mapping.

Exception handling in case of Hibernate and JDBC.

In hibernate, all exceptions are the unchecked exception. So no need to handle at compile time using try-catch or throws keyword. Other hands in case of JDBC the exceptions defined are checked exceptions.


Automatic primary key generation.

Hibernate provides the facility to generate primary keys automatically during storing the data into the database. There are four options to generate a primary key in hibernate.

GenerationType.AUTO –  Generate the primary key using dialect.


First level cache support.

We no need to do any extra configuration. By default Hibernate support first-level cache. In first level cache when we try to retrieve the record first it will fetch the entity from the database second time onwards it will get data from the cache.

The first level cache belongs to session. See the complete example of the first level cache using spring boot and oracle here.

Second-level cache support.

Hibernate support second-level cache. The second-level cache belongs to SessionFactory.

Query language support.

Hibernate supports HQL, Criteria Query etc predefined API which can be directly used to retrieve the data from the database.


Supports EAGER and LAZY fetch type.

HIbernate supports different fetch type (Eager and Lazy) to retrieve the entity. If we define fetch type eager then child entity will also be retrieved along with the parent. In the case of lazy fetch type child will be retrieved on demand. See more details and complete example about Eager and Lazy fetch type here.

Pagination support.

Hibernate has predefined API for pagination support.

Using org.hibernate.Query.

Session session = sessionFactory.openSession();
Query query = sess.createQuery("From Book");
List<Book> bookList = query.list();

Using Criteria.

Criteria criteria = session.createCriteria(Book.class);
List<Book> page= criteria.list();


Transaction Management.

While using we need to write transaction management code(commit and rollback) manually for each save/update/get operation. Since Hibernate can be used with Spring and Spring provide XML and annotation-based transaction management mechanism. No need to write commit and rollback code each and every time.

Using JDBC.

public void saveBook() {
String sql3 = "INSERT INTO Book " + "VALUES (3, 'Alchemist')";


Using Hibernate and Spring.

public void saveBook() {;

That’s all about Benefits of Hibernate over JDBC.

You may like.

Hibernate docs.

JDBC docs.