Sunday, 29 October 2017

Advantages of Hibernate over JDBC

            Let us discuss what are the advantages of Hibernate over JDBC.

Advantages of Hibernate over JDBC: 

 

1) JDBC will throw SQLException which is a checked exception, so you will writing try-catch blocks in a code to handle the exception.  But in hibernate it will handle, it will convert all JDBC exception as unchecked exception. Therefore you no need to write try catch block in a code.  For more detailed about checked and unchecked exception refer this exception questions.

2Hibernate uses the HQL (Hibernate Query Language) which is similar to SQL but HQL provides full support to polymorphic queries. HQL understands object-oriented concepts like inheritance, polymorphism and association.


3)  Hibernate is a database independent because you need not change the HQL(Hibernate Query Language) queries when you change the databases like MySQL, Oracle, PostgreSQL etc. and because of this it's easy to migrate to the new database. It is achieved by using dialect to communicate with database. The database can be specified using dialect in the Hibernate configuration XML file i.e hibernate.cfg.xml as follows,

For MySQL,

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


For PostgreSQL,

<property name=”hibernate.dialect”>org.hibernate.dialect.PostgreSQLDialect</property> 
 
 
         For example, consider the following query. You need to fetch the first 20 records from the table. How this is implemented in different databases is explained below,

SQL Server - 

SELECT TOP 20 column_name FROM table_name ORDER BY column_name ASC

PostgreSQL -
SELECT column_name FROM table_name ORDER BY column_name ASC LIMIT 20;
 
 
In Hibernate this can be done as follows,

  Session.CreateQuery(SELECT t.column_name FROM table_name t ORDER BY t.column_name 
             ASC).SetMaxResults(10).List(); 

 The query statement no need to change the irrespective of database you are using.

4) It is easy to create the association between the tables using Hibernate compared to JDBC.  Associations like one-to-one, one-to-many, many-to-one and many-to-many can be achieved easily in Hibernate by using annotations by mapping the object entity of the required table.

Example of One to Many mapping using annotations,

           There are two tables CART and ITEMS and one to many relationship between them. Created two model classes Cart and Items as follows,
        
   @Entity
   @Table(name="CART")
   public class Cart {

   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   @Column(name="cart_id")
   private long id;
 
   @Column(name="total")
   private double total;
 
   @Column(name="name")
   private String name;
 
   @OneToMany(mappedBy="cart")
   private Set<Items> items;
 
          // Getter Setter methods for properties
  }
 

Item class:--
 
  @Entity
  @Table(name="ITEMS")
  public class Items {

   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   @Column(name="id")
   private long id;
 
   @Column(name="item_id")
   private String itemId;
 
   @Column(name="item_total")
   private double itemTotal;
 
   @Column(name="quantity")
   private int quantity;
 
   @ManyToOne
   @JoinColumn(name="cart_id", nullable=false)
   private Cart cart;
 
   //Hibernate requires no-args constructor
   public Items(){}
 
          //Getter Setter methods
  }


5) Hibernate provides the 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 the application.  There is no such caching mechanism available in the JDBC. This is because Hibernate stores the object in session which is available till the transaction is active.  When a particular query is executing repeatedly, the value stored in the session is used, can not hit the database. Hibernate provides two caching level i.e first level and second level.


6) We can achieve lazy loading of data using Hibernate. Lazy loading concept is to fetch only the necessary object that's required for the execution of an application.
    
     For Example, if there is one parent class and n number of child classes, during an execution, there is no need to load all the child classes.  Instead, only the class that is required for the query need to be loaded. This lazy loading prevents unnecessary loading of objects.  It enhances the performance of the application.

Declaration of lazy loading using fetch=FetchType.LAZY in one-to-many relationship is as follows,
 
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) 
  

 7) Transaction Management:

           A transaction is a group of operation to be performed under one task. If all the operations in a group are 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 transaction is success you need to commit or else if it is failed  you have to rollback the transaction using,
                            con.commit();
                            con.rollback(); 

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


No comments:

Post a Comment