Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In NamedParameterJdbcTemplate String not mapping properly with BeanPropertyRowMapper

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading