Search code examples
javahibernatejdbc

JDBC and Hibernate used for same purpose?


As both are used to interact with databases, are they used for same purpose. kindly explain in detail.


Solution

  • tl;dr

    Hibernate is one of many frameworks written on top of JDBC, designed to make using JDBC easier for your app to exchange data with a database.

    diagram of Java database technology stack

    JDBC

    JDBC is the standard way to connect your Java app to a relational database.

    • You write your SQL commands as text in Java String objects. JDBC conveys that command to the database.
    • Any errors reported by the database are wrapped as objects by JDBC and returned to your Java apps.
    • If your SQL runs successfully in the database, JDBC retrieve the results from the database, and provides that data as a result set to your Java app.

    You can call JDBC commands yourself directly from your own Java code. Many people do this.

    Frameworks built on top of JDBC

    However, writing the SQL code and retrieving the results can make for tedious coding. So many Java frameworks have been written by various people to assist in generating the embedded SQL code and in retrieving results. These frameworks are written on top of JDBC, making JDBC calls on your behalf. Many people use these.

    Some of these frameworks implement interfaces defined in a standard. Jakarta Persistence, formerly known as Java Persistence API (JPA), is a quite popular standard. See specification. Another such standard is Java Data Objects (JDO).

    Hibernate is an implementation of the Jakarta Persistence specification. Other implementations include EclipseLink, OpenJPA, and more. See What is a JPA implementation?. Note that these implementations may deliver features beyond those required by the standard.

    You may address any of these Jakarta Persistence implementation libraries directly. Or you may choose to use only the Jakarta Persistence API in your code. If using only the Jakarta Persistence API, you can later switch out one implementation for another without breaking your app.

    And note that all of these frameworks, including Hibernate, are using JDBC. You must supply a JDBC driver specific to your particular database engine in order to use these frameworks such as Hibernate.

    Other frameworks have been produced outside the the Jakarta Persistence standard. Some are quite popular, such as Jdbi, JOOQ, MyBatis, and Spring Data.

    And we have database migration tools that also use JDBC, such as Flyway and Liquibase.