JDBC (Java Database Connectivity) is the standard Java API for interacting with relational databases, and Spring JDBC is essentially a higher-level abstraction over plain JDBC provided by the Spring Framework.
Why do we have Spring JDBC?
Plain JDBC
Using plain JDBC involves a lot of boilerplate code:
- Load drive
- Define connection URL
- Opening/closing database connections
- Handling exceptions
- Creating
PreparedStatement
- Extracting results from
ResultSet
Example with plain JDBC:
Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
// map the result
}
rs.close();
ps.close();
conn.close();
That’s a lot of repeated code just for querying a database.
Spring JDBC
Spring JDBC simplifies this by:
- Spring manages connections and resources for you
- Providing templates like
JdbcTemplate
to handle repetitive tasks - Reducing boilerplate code
- Providing better exception translation
Example with Spring JdbcTemplate
:
User user = jdbcTemplate.queryForObject(
"SELECT * FROM users WHERE id = ?",
new Object[]{id},
new BeanPropertyRowMapper<>(User.class)
);
Much cleaner and easier to maintain.
Back to parent page: Spring and Spring Boot
Web_and_App_Development Java Java_Framework Spring_Framework