DClick

Spring & JDBC


Twitter!

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

JAVA:
  1. PreparedStatement ps = connection.prepareStatement("Select name, email from t_users where status = ?");
  2. ps.setInt(1, new Integer(1));
  3.  
  4. ResultSet rs = ps.executeQuery();
  5. List<User> users = new ArrayList<User>();
  6.  
  7. while (rs.next()) {
  8.     User user = new User();
  9.     user.setName(rs.getString("name"));
  10.     user.setEmail(rs.getString("email"));
  11.     users.add(user);
  12. }
  13.  
  14. 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:

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

RowMapper sample:

JAVA:
  1. public class UserRowMapper implements RowMapper {
  2.     @Override
  3.     public Object mapRow(ResultSet rs, int numRow) throws SQLException {
  4.         User user = new User();
  5.         user.setName(rs.getString("name"));
  6.         user.setEmail(rs.getString("email"));
  7.  
  8.         return user;
  9.     }
  10. }

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

Compartilhe:

  • RSS
  • Twitter
  • del.icio.us
  • Facebook
  • MySpace
  • LinkedIn
  • Google Bookmarks
Por Bruno Fuster em 15/January/2009 | Comentar | Trackback


Other Languages:

Um comentário para “Spring & JDBC”


Parabéns pelo excelente blog!! Aproveitando a deixa, se vc tiver qualquer coisa pra vender ou estiver procurando carros, imóveis, etc, acesse o Noticie Classificados, abraço!

Adicionar comentário

(requerido)
(requerido, não será publicado)