15 reasons why we need to choose Hibernate over JDBC

Have you ever feel irritated by repeating the same lines of code over and over again in your application for fetching data from the database?

Are you struggling to map objects to your database tables?

Is it difficult for you to implement oops with your JDBC code?

Does it takes too much of rework while migrating from one database to another?

Have you ever found it difficult to create associations between tables using JDBC?

If you are wondering whether there is a way to avoid these problems, I am very much pleased to inform you that there is an ORM tool ‘HIBERNATE’ to overcome this.

Before getting into that, I would like to explain what is Hibernate and JDBC.

What is JDBC?

JDBC stands for Java Database Connectivity. It is a free open source application programming interface for Java which enables the application to access the database. It enables the developers to create queries, update data to the relational database using a Structured Query Language (SQL).

JDBC Workflow

Source: avaldes

Opens a database connection

Sends SQL queries to database using a JDBC driver

JDBC driver connects to database

Executes the queries to get the result set

Sends the data to the application via the driver manager

When results are returned, then it processes the data

Finally, the connection is closed

What is Hibernate?

Hibernate is a free open source object-relational mapping library for Java which is designed to map objects to an RDBMS and to implement the object-oriented programming concepts in a relational database.

Hibernate Workflow

Unlike JDBC Hibernate connects with the database itself and uses HQL (Hibernate Query Language) to execute the queries and then it maps the results to the Java objects.

The results are mapped to objects based on the properties given in the Hibernate configuration XML file.

The database connection from an application is created using session which also helps in saving and retrieving the persistent object.

Session factory is an interface which helps to create an instance of a session. There must be only one session factory per database. For example, if you are using MySQL and ORACLE in your application, one session factory for MySQL and one session factory for ORACLE is maintained. There will not be more than one session factory per MySQL alone.

Why is Hibernate better than JDBC?

1. Hibernate mainly solves the object-relational impedance mismatch problems which arise when a relational database is connected by an application written in object oriented programming language style. Object-relational impedance mismatch includes mismatches arises due to data type differences, manipulative differences, transactional differences, structural and integrity differences. Click here to see more details.

2. In JDBC you need to write code to map the object model’s data representation to a relational model and its corresponding schema. Hibernate itself maps the Java classes to the database tables using XML configuration or by using annotations. The following example will help you understand how object mapping is done in Hibernate

JDBC:List<User> users=new ArrayList<User>();

while(rs.next()) {

User user = new User();

user.setUserId(rs.getString(“UserId”));

user.setName(rs.getString(“FirstName”));

user.setEmail(rs.getString(“Email”));

users.add(user);

}

Hibernate:

@Entity

@Table(name=”user”)

public class UserModel {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private BigInteger id;

@NotEmpty

@Column(name=”email”,unique=true)

private String email;

@NotEmpty

@Column(name=”name”)

private String name;

public BigInteger getId() {

return this.id;

}

public void setId(BigInteger id) {

this.id = id;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public String getName() {

return this.name;

}

}

In the above example, you can see that by using JDBC you need to set every property of an object on fetching the data each and every time. But in Hibernate we need to map the table with the java class as mentioned above.

3. Hibernate uses HQL (Hibernate Query Language) which is similar to SQL but Hibernate’s HQL provides full support to polymorphic queries. HQL understands object-oriented concepts like inheritance, polymorphism, and association. For detailed understanding of polymorphic HQL queries refer this link.

4. Hibernate’s code is database independent because you need not change the HQL queries (exceptions are there) when you change the databases like MySQL, oracle, etc and hence it is easy to migrate to a new database. It is achieved by using a dialect to communicate with the database. The database can be specified using dialect in the Hibernate configuration XML as follows.

<property name=”dialect”>org.hibernate.dialect.MySQL</property>

For example, consider the following scenario. You need to fetch the first 10 entries of a table. How this is implemented in different databases is explained below

In JDBC as mentioned above for inserting a record, you will be creating a prepared statement And will be setting each column of a table. If the number of columns increases the statements will also increase. But in Hibernate we just need to save the object as follows.

persist(Object);

7. We can achieve lazy loading of data using Hibernate i.e data can be loaded only when it is needed. Consider an example where there is a list of users in the user table. The identity proof documents uploaded by the users are stored in the identity_proof table. The user has a ‘one to many’ relationships with the identity_proof. In this case, the user is the parent class and identity_proof is the child class.If you fetch the parent class i.e the user, all the documents associated with the user will also be fetched. Imagine the size of each document. As the number of documents increases the size of data to be processed also increases and hence it will slow up the application.

How Hibernate helps here is you can specify the fetch type for data as LAZY. If you do so when you fetch user, documents will not be fetched. You can fetch the documents where you want using Hibernate’s initialize() method.

// To fetch user with document use initialize() method as follows
getHibernateTemplate().initialize(user.getProofList());

8. JDBC will throw SQLexception which is a checked exception. So you will be writing “try-catch” blocks in your code. Hibernate handles this by converting all JDBC exception as an unchecked exception. Therefore you need not waste your time in implementing this try catch blocks. If you are not familiar with the term checked and unchecked exceptions, please refer this link for your understanding.

9. Transaction Management:

Source: Devarticles

A transaction is a group of operation to be performed under one task. If all the operations in a group are a success then the task is finished and the transaction is successfully completed. If one of the operation is failed then the whole task is failed and hence the transaction is also failed. In JDBC if a transaction is a success you need to commit or else if it is failed you have to rollback the transaction using following commands.

con.commit();

con.rollback();

In Hibernate you don’t have to commit and rollback these transactions as it is implicitly provided.

10. It is easy to create an association between the tables using Hibernate than JDBC. Associations like one-to-one, one-to-many, many-to-one, many-to-many can be achieved easily in Hibernate by using annotations by mapping the object entity of the required table. To read more about these associations, kindly go through this link. An example for creating association is given below

Hibernate provides caching mechanism which helps to reduce the number of hits as much as possible that your application makes with the database server. This will have a considerable amount of effect regarding the performance of your application. There is no such caching mechanism available in JDBC. This is because Hibernate stores the object in session which is available till the transaction is active. When a particular query is executed repeatedly, the value stored in the session is used. When a new transaction begins, the object is fetched again from The database and is stored in the session. In fact, two levels caches are provided by Hibernate.To know more about Hibernate caching, refer this link.

12. Database versioning is an important feature of Hibernate. Hibernate enables the developer to define version type field to an application which is updated when the data is updated every time. The advantage is if two different users retrieve same data and then modify it and one user saved his modified data to the database before the other user, the version is updated. Now when the other user tries to saves his data, it will not allow to save it because this data is not an updated data. In JDBC this check is to be performed by the developer.

13. Hibernate provides a library called “Envers”which enables us to achieve audit functionality easily. It creates tables and stores the audited data with version number from where we can track the changes made to the entity. Let me explain how auditing is done using envers

When we add @Audited annotation in our entity class Hibernate will create a table called User_AUD to store the audited entries. The table will contain two additional fields REVTYPE and REV. REVTYPE is the type of the revision, it can store the values as add for inserting, mod for modifying and del for deleting. The REV field contains the revision number of the stored entry.Hibernate creates an extra table called REVINFO in which the REV number is mapped with a timestamp when the change of the entity happened. You can also customize the revision table using @RevisionEntity.

14. Hibernate provides support to JPA annotations like @Entity, @Table, @Column, etc. These annotations make the code portable to other ORM frameworks. You can find some of the annotations explained with an example in this link

15.Connection pooling:
As explained in Wikipedia, connection pooling is a mechanism in which the database
connections when created are stored in the cache by an external tool so that these connections can be reused from the cache when the application tries to connect to the same database in future. Connection pooling helps to increase the performance. We can achieve this connection pooling in Hibernate. Below is the list of connection pools supported by HibernateC3p0 Apache DBCP Proxool
You need to set the properties in Hibernate.cfg.xml file as required to enable connection Pooling. A sample property is shown below.

From the above-mentioned points, it is crystal clear that Hibernate will definitely increase the performance of your application and help you to reduce the development time for your application and hence the cost. So by considering the above-mentioned advantages, I will recommend everyone to prefer Hibernate over JDBC.

Note:

You can find some of the other open source persistence frameworks in JAVA in this link.

About us

Habile Technologies brews innovation and offers the perfect mix of technology, competitive business edge and strategy. With a proven track record of happy clients, we are proudly the best technology partner for your organisation.

how can we help you?

Tell us about your requirement and we’ll offer you the best possible solution. Get in touch now.

Habile Technologies - A digital technologies services and products company with more than 9 years of solid experience. Habile Technologies leverages it technical expertise to help clients outperform competition and be a leader in the innovation curve.