What is the main difference between Spring JDBC VS JDBC?
The short answer on the fundamental difference between JDBC and Hibernate is that Hibernate performs an object-relational mapping framework, while JDBC is simply a database connectivity API. The long answer requires a history lesson on database access with Java.
Spring JDBC only helps with the connection to the database and with executing queries on this database. Spring Data JPA wants to help you manage your JPA based repositories. It wants to remove boilerplate code, make implementation speed higher and provide help for the performance of your application.
It provides methods to query and update data in a database and is oriented toward relational databases. JDBC offers a natural Java interface for working with SQL. JDBC is needed to provide a “pure Java” solution for application development.
JdbcTemplate provides a great exception handling mechanism that is more specific to deal with the database, it converts the standard JDBC SQLExceptions into RuntimeExceptions which are generic and more informative, allowing developers to better identify the error.
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.
Spring JDBC value-add provided by the Spring Framework's on top JDBC layer
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With