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.

Book.java

package javatute;
 
@Entity
@Table(name = "book")
public class Book {
	 
	 @Id
	 @GeneratedValue(strategy = GenerationType.AUTO)
	 private int bookId;
	 
	 @Column(name="book_name")
	 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.setBookId(109);

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

		Transaction transaction = session.beginTransaction();

		session.save(book);

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

		transaction.commit();

		session.close();

		factory.close();
	}
}

 

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

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
<session-factory>
 
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
 
<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="hbm2ddl.auto">create</property>
 
 <mapping class="onetomany.Book" />
 
 <mapping class="onetomany.Story" />
 
</session-factory>
 
</hibernate-configuration>

 

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 Book.java and HibernateSaveEntityExample.java.

 

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')";
			statement.executeUpdate(sql1);

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

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

                        connection.commit();

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

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

			}

		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			try {
				connection.close();
			} catch (SQLException e) {

				e.printStackTrace();
			}
		}

	}
}

 

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.setBookId(109);

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

			Transaction transaction = session.beginTransaction();

			session.save(book);
			

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

		} catch (Exception e) {

			e.printStackTrace();

		} finally {

			session.close();

			factory.close();

		}

	}
}

 

Automatic table creation.

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

Possible value hbm2ddl.auto
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.
GenerationType.IDENTITY.
GenerationType.SEQUENCE.
GenerationType.TABLE.

 

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");
query.setFirstResult(0);
query.setMaxResults(5);
List<Book> bookList = query.list();

Using Criteria.

Criteria criteria = session.createCriteria(Book.class);
criteria.setFirstResult(0);
criteria.setMaxResults(10);
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')";
statement.executeUpdate(sql3);
connection.commit();

}

Using Hibernate and Spring.

@Transactinal
public void saveBook() {
session.save(book);
}

That’s all about Benefits of Hibernate over JDBC.

You may like.

Hibernate docs.

JDBC docs.