Below is the simple query to get a list of strings.
String sqlQuery = "SELECT TAGS FROM FIN_REQUEST WHERE IS_CORPORATE_CONTENT IS TRUE AND TAGS IS NOT NULL";
List<String> data1 = namedParameterJdbcTemplate.query(sqlQuery, BeanPropertyRowMapper.newInstance(String.class));
List<String> data2 = namedParameterJdbcTemplate.query(sqlQuery, new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString(1);
}
});
data1 gives an empty list while data2 is giving proper results. I want to avoid RowMapper and use BeanPropertyRowMapper instead.
BeanPropertyRowMapper
, as the name implies, is for mapping columns to bean properties. You don't have a wrapper with a field of type String named tags
. You are just returning a single String
. So you cannot use the BeanPropertyRowMapper
.
If you want to use it you need to create a wrapper object, which is probably not what you want. So you need to use the RowMapper
. Assuming you are on Java 8 or up you can just use a lambda instead of in anonymous class.
List<String> data2 = namedParameterJdbcTemplate.query(sqlQuery, (rs, row) -> rs.getString(1));
However I see no use for the NamedParameterJdbcTemplate
here (there are no named parameters) so you could also use the regular JdbcTemplate
instead and use one of its methods.
List<String> data2 = jdbcTemplate.queryForList(sqlQuery, String.class);