Difference Between JDBC and Hibernate

JDBCObject Oriented ProgrammingProgramming

JDBC is acronym of Java database connectivity. It is used to connect your application to the database and transactions . It is an open source Java api.  

Hibernate is also used for connect your application to database and to do database related transactions but with different approach. It has a object relationship library which mapped the tables and columns of the database with the java object. It enables object oriented programming in database. Hibernate provides HQL to access the data from the database.

Sr. No.
Key
JDBC
Hibernate

1

Basic 

It is database connectivity technology 

It is a framework,

2

Lazy Loading 

It does not support lazy loading 

Hibernate support lazy loading 

3

Transaction management 

We need to maintain explicitly database connection and transaction.  

Hibernate itself manage all transaction 

4.

Caching 

We need to write code for implementing caching  

Hibernates provides two types of caching :

First level Cache 

Second level cache


No Extra code is required to use first level cache.

5.

Performance 

Low performance

High Performance 

Example of Hibernate

@Entity
public class User {
   @Id
   Integer id;
   String name;
   public Integer getId() {
      return id;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.journaldev.hibernate.util.HibernateUtil;
public class HibernateConnectionExample {
   public static void main(String[] args) {
      //get session factory to start transcation
      SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
      Session session = sessionFactory.openSession();
      Transaction tx = session.beginTransaction();
      User user = (User) session.get(User.class, new Integer(2));
      System.out.println("User ID= "+user.getId());
      System.out.println("User Name= "+user.getName());
      //Close resources
      tx.commit();
      sessionFactory.close();
   }
}

Example of JDBC Connection

class JDBCConnectionExample {
   public static void main(String a[]) {
      String url = "jdbc:oracle:thin:@localhost:1521:local";
      String user = "sys";
      String password = "abc123";
      String sql = "select * from user";
      Connection con=null;
      try {
         DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
         //Reference to connection interface
         con = DriverManager.getConnection(url,user,password);
         Statement st = con.createStatement();
         int respCode = st.executeUpdate(sql);
         con.close();
      }
      catch(Exception ex) {
         System.err.println(ex);
      }
   }
}
raja
Published on 21-Jan-2020 11:47:41
Advertisements