What is the main difference between Spring JDBC VS 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.