Saturday, September 14, 2013

Spring JDBCTemplate with Lambdas

Here is an example of the use of JDBCTemplate in Spring 3:

Person person = jdbcTemplate.queryForObject(
                "select first_name, last_name, age from t_person where id = ?",
                new Object[]{1212L},
                new RowMapper() {
                     public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
                        
Person person = new Person(
                             rs.getString("first_name"),
                             rs.getString("last_name"),
                             rs.getInt("age")
                         );
                         return person;
                     }
                 });


What will our SpringTemplate code look like next year when we can utilize Java 8 lambdas? 1/3 fewer lines of code.

Person person = jdbcTemplate.queryForObject(
                     “select first_name, last_name, age from t_person where id = 42”,
                     (rs, rowNum) -> {
                     return new Person(
                        rs.getString("first_name"),
                         rs.getString(“last_name”),
                         rs.getInt(“age”)
                     );
                 });