Difference Between Spring JDBC Vs Plain JDBC? Difference Between Spring JDBC Vs Plain JDBC? spring spring

Difference Between Spring JDBC Vs Plain JDBC?


Let me show you some simple example using JDBC:

final Connection connection = ds.getConnection();try {    final Statement statement = connection.createStatement();    try {        final ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) FROM Orders");        try {            resultSet.next();            final int c = resultSet.getInt(1);        } finally {            resultSet.close();        }    } finally {        statement.close();    }} finally {    connection.close();}

It's much better when try-with-resources though:

try (        Connection connection = ds.getConnection();        Statement statement = connection.createStatement();        ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) FROM Orders");) {    resultSet.next();    final int c = resultSet.getInt(1);}

Of course you can extract common code and use template method Design Pattern. Effectively you'd reinvent JdbcTemplate:

final int c = new JdbcTemplate(ds).queryForInt("SELECT COUNT(*) FROM Orders");

Also Spring JDBC provides exception translation (no more checked SQLException and differences between databases/dialects) and simple ORM capabilities.


1.) Spring jdbc module is an abstraction layer on top of jdbc technology, this layer avoids the boiler plate code used in jdbc programming.2.) Spring ORM module is an abstraction layer on top ORM tools.3.) When working with ORM tools like a hibernate again we have a Boiler plate code this spring ORM layer avoids boiler plate code of ORM tools.


Spring JDBC value-add provided by the Spring Framework's on top JDBC layer

  1. Define connection parameters
  2. Open the connection
  3. Specify the statement
  4. Prepare and execute the statement
  5. Set up the loop to iterate through the results (if any)
  6. Do the work for each iteration
  7. Process any exception
  8. Handle transactions
  9. Close the connection

Basically , you don't need to worry about managing and suffering from infrastructure/plumbing code and purely worry about data and its mapping to objects.

Spring utilizes Template pattern to hide all low level details while giving you extension hooks to extend and work with JDBC.

Also, there is a well defined API for database exceptions, that is really developer-friendly when compared to exception hierarchy provided by low level JDBC API's