@brunofuster

www.wesaveapp.com

Archive for the ‘spring’ Category

Spring & JDBC Template

leave a comment »

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

public List<User> getUsers() {

    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:

public List<User> getUsers() {
    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

Advertisements

Written by brunofuster

March 12, 2009 at 12:14 pm

Posted in java, jdbc, spring