2

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

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • briefly JDBC is using standard SQL query and the result(select) have to be manually added into utility classes. Hibernate use for query a specific language JSQL(somehow similar to SQL syntax) which is latter translated into SQL. But Hibernate operate with `objects` so before mapping classes are required. Mapping classes are populated directly from queries (select).. Also JPQL is independent related to any particular SQL implementation (Oracle, MSQL) but some specific futures on specific SQL may not be available (unless use raw SQL) – Traian GEICU Aug 08 '21 at 15:48
  • 4
    This is something you can look up in the internet easily. Also, a duplicate of this question ([JDBC VS Hibernate](https://stackoverflow.com/questions/28163670/jdbc-vs-hibernate)) has already been closed. – Giorgi Tsiklauri Aug 08 '21 at 16:52
  • I am voting to re-open. This question asks for a big-picture view of how Hibernate and JDBC relate to one another. The [other Question](https://stackoverflow.com/questions/28163670/jdbc-vs-hibernate) asks for “pros and cons of Hibernate VS Java JDBC” in a heated opinionated spirit. While that other Question should indeed be closed, this Question here is quite different. This Question here can be addressed in a succinct factual manner, without any of the other Question’s “what’s better, which sucks” argumentation. – Basil Bourque Aug 08 '21 at 17:01

3 Answers3

7

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.

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • It might be worthwhile to explicitly point out that Hibernate uses JDBC to connect to the database. I get the feeling a lot of people asking this type of question think it is an either/or situation. – Mark Rotteveel Aug 08 '21 at 17:09
  • 2
    @MarkRotteveel That was my entire point, yet somehow I failed to say so explicitly. So thank you for the comment. I revised the Answer. – Basil Bourque Aug 08 '21 at 17:39
1

JDBC and Hibernate were used for the same purpose, it's to interact with the database, however, each one has its method to interact with the database, in addition, each one has its own concept

Let's talk about ORM first:

Object Relational Mapping (ORM) is a functionality which is used to develop and maintain a relationship between an object and relational database by mapping an object state to database column. It is capable to handle various database operations easily such as inserting, updating, deleting etc.

ORM Frameworks Following are the various frameworks that function on the ORM mechanism: -

  1. Hibernate
  2. TopLink
  3. ORMLite
  4. iBATIS
  5. JPOX

What is JDBC? JDBC allows the program to interact with the database, the API enables to execute SQL statements from java program, The JDBC API enables whether to update, insert, delete or fetch data from the database, in short, we called CRUD(Create, read, update and delete)

enter image description here

java.sql contains classes and interfaces for JDBC API as shown below:

  1. Driver interface
  2. Connection interface
  3. Statement interface
  4. PreparedStatement interface
  5. CallableStatement interface
  6. ResultSet interface
  7. ResultSetMetaData interface
  8. DatabaseMetaData interface
  9. RowSet interface

To discover each one of these classes and interfaces, I would suggest reading a book named JDBC Access with Java by Graham, Hamilton Rick Cattell, and Maydene Fisher

chu3la
  • 18
  • 5
0

The question is not either - or, but the options are

  • use JDBC
  • use ORM tool such as Hibernate that uses JDBC under the cover

The choice is driven by the position of the database in the application.

If the application considers the database as persistence only or if it even don't care what RDBM is used you typically choose some ORM tool.

Often there is an argument that using ORM you trade some flexibility and control against less code required.

This aspect and the consequences is illustrated below on the example of sample scenario of inserting and selecting data.

In pure SQL it would be

insert into customer(cu_first_name,cu_last_name) values ('Mike Y.','Batis');
insert into customer(cu_first_name,cu_last_name) values ('Henry','Iber-Nate');
insert into customer(cu_first_name,cu_last_name) values ('John D.','Beece');
commit;

select * from customer;

In the code snippets I use Groovy to make the code more compact and to concentrate on the differences.

All the scripts have the connection set up and the data are defined:

 def data = [ [first : 'Mike Y.', last : 'Batis'], [first : 'Henry', last : 'Iber-Nate'], [first : 'John D.', last : 'Beace'], ]

Plain JDBC

def stmt = con.prepareStatement("insert into customer (cu_first_name,cu_last_name) values (?,?)") 

data.each  {
   stmt.setString(1,it.first) 
   stmt.setString(2,it.last)          
  stmt.executeUpdate()
}
con.commit()
stmt.close()

stmt = con.prepareStatement("""select cu_id, cu_first_name, cu_last_name from customer
where cu_id between ? and ?""")

stmt.setInt(1,1)
stmt.setInt(2,3)

def rs = stmt.executeQuery()

while(rs.next())
  {
   println "cu_id= ${rs.getInt(1)} fname= ${rs.getString(2)} lname= ${rs.getString(3)}"
  }
rs.close()
stmt.close()

JDBCTemplate

String insertQuery = "insert into customer (cu_first_name,cu_last_name) values (?,?)";

data.each  {
     jdbcTemplate.update(insertQuery, it.first, it.last);     
}

def sql = """select cu_id, cu_first_name, cu_last_name from customer
where cu_id between ? and ?"""

def list = jdbcTemplate.queryForList(sql, 1, 3);
println list

Hibernate

Session session =  sessionFactory.getCurrentSession()
session.beginTransaction();

data.each  {
    Customer cu = new Customer(fname: it.first, lname: it.last)
    session.save(cu); 
}

List result = session.createQuery("from Customer where cu_id between :from and :to")
              .setParameter("from", 1)
              .setParameter("to", 3)
              .list()
result.each {println "selecting Customer id: ${it.id} fname: ${it.fname} lname: ${it.lname}"}

Summary

Using plain JDBC you have a full control but you need to care about everything, set the bind variables individually, closing the result sets and statements.

In JDBCTemplate you still use the same SQL but overhead is much less and the resources are closed automatically.

In Hibernate you don't need to write INSERT at all and the SELECT may start with from - you need not to care about the columns. (Note that other options native query and criteria query are available as well)

What happens below the hood depends on the database - I'm discussing here the Oracle RDBMS.

The JDBC code leads to one parse of the INSERT statement that is three times executed and than closed.

In JDBCTemplate and Hibernate the INSERT statement is three times parsed, executed and closed.

The same is valid for the SELECT statement.

This sound like a big performance difference, but (at least in Oracle) the closed cursor typically remains cached, so the next parse can be done very efficiently. (aka soft parse)

Marmite Bomber
  • 19,886
  • 4
  • 26
  • 53