Search code examples
springjava-8spring-jdbc

Replacing RowMapper object with java 8 lambda expression


I am using Spring JdbcTemplate class in my project.I have the following code:

       List<PersonDTO> personList = jdbcTemplate.query(query, new RowMapper<PersonDTO>() {

            @Override
            public PersonDTO mapRow(ResultSet rs, int rowNumber) throws SQLException {
                PersonDTO personDTO = new PersonDTO ();
                personDTO.setPerId(rs.getString("COL_ONE"));  
                personDTO.setIdTypeCd(rs.getString("COL_TWO")); 
                return personDTO;
            }
        });

Now I want to replace the anonymous class RowMapper with java8 lambda expression something like this:

Runnable r1 = () -> {
        System.out.println("My Runnable");
    };

Is it possible?


Solution

  • AFAIK RowMapper is a functional interface, so this would work. lambda expression can't declare checked exceptions, so you will need to wrap that...

    jdbcTemplate.query(query, (ResultSet rs, int rowNumber) -> {
                PersonDTO personDTO = new PersonDTO ();
                personDTO.setPerId(rs.getString("COL_ONE"));  
                personDTO.setIdTypeCd(rs.getString("COL_TWO")); 
                return personDTO;
    });
    

    The comments are spot on: since that functional interface already declares to throw the exception, there is no need to catch it.