Técnico

Spring & JDBC

The Spring Framework makes JDBC development easier by using IoC to eliminate low-level code. If you don’t use an ORM framework, this API is highly recommended. Now let’s see a comparison sample between pure JDBC and JDBC with Spring JdbcTemplate class:


Example 1: Creating a list of objects with pure JDBC

PreparedStatement ps = connection.prepareStatement("Select name, email from t_users where status = ?");
ps.setInt(1, new Integer(1));

ResultSet rs = ps.executeQuery();
List users = new ArrayList();

while (rs.next()) {
User user = new User();
user.setName(rs.getString("name"));
user.setEmail(rs.getString("email"));
users.add(user);
}

return users;

Besides, you have to control connections opening and closing.

Example 2: Creating a list of objects with Spring and JDBC:

We have to use the JdbcTemplate class that can be instantied by injecting your datasource (new JdbcTemplate(dataSource)). Then you should create a new class that implements the RowMapper interface for the objects creation. After that, you can get the list of objects with just one line of code:


return (List) jdbcTemplate.query("Select name, email from t_users where status = ?",
new Object[] { new Integer(1) }, new UserRowMapper());

RowMapper sample:


public class UserRowMapper implements RowMapper {
@Override
public Object mapRow(ResultSet rs, int numRow) throws SQLException {
User user = new User();
user.setName(rs.getString("name"));
user.setEmail(rs.getString("email"));

return user;
}
}

Complete reference: http://static.springframework.org/spring/docs/2.0.x/reference/jdbc.html

1 Comments

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Compartilhe isso: