I have a below code snippet (taken from Mykong tutorial: Spring Boot JDBC Examples):
public class JdbcBookRepository implements BookRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<Book> findAll() {
return jdbcTemplate.query(
"select * from books",
(rs, rowNum) ->
new Book(
rs.getLong("id"),
rs.getString("name"),
rs.getBigDecimal("price")
)
);
}
@Override
public List<Book> findByNameAndPrice(String name, BigDecimal price) {
return jdbcTemplate.query(
"select * from books where name like ? and price <= ?",
new Object[]{"%" + name + "%", price},
(rs, rowNum) ->
new Book(
rs.getLong("id"),
rs.getString("name"),
rs.getBigDecimal("price")
)
);
}
}
You can see the duplicate code here:
(rs, rowNum) ->
new Book(
rs.getLong("id"),
rs.getString("name"),
rs.getBigDecimal("price")
)
In order to remove duplication, I am trying to refactor this code and declare the below function using functional style - like below:
BiFunction<ResultSet,Integer,Book> rowExtractor = (rs, rowNum) ->
new Book(
rs.getLong("id"),
rs.getString("name"),
rs.getBigDecimal("price")
);
but Java compiler complains: java: unreported exception java.sql.SQLException; must be caught or declared to be thrown
My question: Is it possible to somehow do it elegantly in java using functional style ?
I know that I can do it "old way" like below, but I wanted to try functional interfaces:
RowMapper<Book> extractor1 = new RowMapper<>(){
@Override
public Object mapRow(ResultSet rs, int i) throws SQLException {
return new Book(
rs.getLong("id"),
rs.getString("name"),
rs.getBigDecimal("price")
);
}
};
Create a RowMapper
as below,
RowMapper<Book> bookRowMapper = (rs, rowNum) ->
new Book(
rs.getLong("id"),
rs.getString("name"),
rs.getBigDecimal("price")
);
And use as below,
jdbcTemplate.query("select * from books", bookRowMapper);
jdbcTemplate.query(
"select * from books where name like ? and price <= ?",
new Object[]{"%" + name + "%", price},
bookRowMapper
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With