15 reasons why we need to choose Hibernate over JDBC

Hey Java Developer,

  1. 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?
  2. Are you struggling to map objects to your database tables?
  3. Is it difficult for you to implement oops with your JDBC code?
  4. Does it takes too much of rework while migrating from one database to another?
  5. 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?

rRo2xK

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

Java_jdbc

Source: avaldes

  1. Opens a database connection
  2. Sends SQL queries to database using a JDBC driver
  3. JDBC driver connects to database
  4. Executes the queries to get the result set
  5. Sends the data to the application via the driver manager
  6. When results are returned, then it processes the data
  7. Finally, the connection is closed

What is Hibernate?

Hibernate-ORM

Source: J2eebrain

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

hibernate2

Source: Cloudsopedia

  1. 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.
  2. The results are mapped to objects based on the properties given in the Hibernate configuration XML file.
  3. The database connection from an application is created using session which also helps in saving and retrieving the persistent object.
  4. 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
  • Mysql: SELECT column_name FROM table_name ORDER BY column_name ASC LIMIT 10;

  • Sql Server: SELECT TOP 10 column_name FROM table_name ORDER BY column_name ASC;

  • In Hibernate, this can be done as follows
  • Session.CreateQuery(“SELECT E.id FROM Employee E ORDER BY E.id ASC”).SetMaxResults(10).List();

  • Thus your query statement need not change irrespective of the database you are using.
                      • 5.Hibernate minimize the code changes when we add a new column in the database table. The changes to be done is given below.
                      • JDBC:
                        • You have to add a new field in your POJO class.
                        • Change your JDBC method that performs the “select” to include the new column.
                        • Change your JDBC method that performs the “insert” to add a new value into the new column.
                        • Change your JDBC method that performs the “update” to update an existing value in your new column.

                        Hibernate:

                        • Add the new field into your POJO class.
                        • Modify the Hibernate XML mapping file to include the new column

    Thus database table changes can be easily implemented using Hibernate with less effort.

                      • 6. Hibernate reduces the amount of repeating lines of code which you can often find with JDBC. For your understanding, I have mentioned a simple scenario below.
                      • Class.forName(“com.mysql.jdbc.Driver”);Connection con = DriverManager.getConnection( “jdbc:mysql://localhost:3306/sonoo”,

                        “root”,”root”);

                        PreparedStatement stmt=con.prepareStatement(“insert into Emp values(?,?)”);

                        stmt.setInt(1,101);

                        stmt.setString(2,”Ratan”);

                        stmt.executeUpdate();

                        con.close();

                        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.

    // Declaring fetch type for one to many association in your POJO
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set ProofList = new HashSet();

    // 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:
                        2b2V3j

    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

    @Entity
    @Table(name = “college”)
    public class College {
    @Id
    @GeneratedValue
    private Integer id;
    @Column(name=”college_name”)
    private String name;
    @OneToMany(mappedBy=”college”, cascade=CascadeType.ALL)
    private Set departments;
    }

    @Entity
    @Table(name = “department”)
    public class Department {
    @Id
    @GeneratedValue
    private Integer id;
    @Column(name=”department_name”)
    private String departmentname;
    @ManyToOne
    @JoinColumn(name = “college_id”)
    private College college;
    }

  • 11. Hibernate caching:
    main-qimg-0e98546368ea9b013384b7fb0b145199

 

 

Source: Quora

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

@Entity
@Table(name = “User”)
@Audited
public class User {
// … the body of the entity
}

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

<property name=”hibernate.c3p0.min_size”>5</property>
<property name=”hibernate.c3p0.max_size”>20</property>
<property name=”hibernate.c3p0.timeout”>300</property>
<property name=”hibernate.c3p0.max_statements”>50</property>
<property name=”hibernate.c3p0.idle_test_period”>3000</property>

Conclusion:  

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.

2 Comments

Leave a Reply

how can we help you?

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