Explain Spring JDBC API and its classes.
Spring JDBC is a part of the Spring Framework that provides a simplified approach to working with relational databases using JDBC (Java Database Connectivity). It helps to reduce boilerplate code and manage resources effectively, making it easier to interact with databases in Java applications.
JdbcTemplate:
query()
, update()
, execute()
, and batchUpdate()
.RowMapper:
public class UserRowMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
return user;
}
}
PreparedStatementCreator:
PreparedStatement
objects.ResultSetExtractor:
ResultSet
.ResultSet
and return a single object or a collection of objects.SimpleJdbcInsert:
SimpleJdbcCall:
NamedParameterJdbcTemplate:
JdbcTemplate
that supports named parameters in SQL queries.Here’s a simple example of how to use JdbcTemplate
to query a database:
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class UserDao {
private JdbcTemplate jdbcTemplate;
public UserDao(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<User> getAllUsers() {
String sql = "SELECT id, name FROM users";
return jdbcTemplate.query(sql, new UserRowMapper());
}
private static class UserRowMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
return user;
}
}
}
Spring JDBC provides a powerful and flexible way to interact with relational databases in Java applications. By using its template classes and various helper interfaces, developers can write cleaner, more maintainable code while leveraging the full power of JDBC.