Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing RowMapper object with java 8 lamda 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 lamda expression something like this:

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

Is it possible???

like image 690
Sumit Ghosh Avatar asked Apr 04 '18 12:04

Sumit Ghosh


1 Answers

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.

like image 131
Eugene Avatar answered Jan 01 '23 02:01

Eugene