Search code examples
javaspring-jdbc

Сannot get Float data type from NamedParameterJdbcTemplate


I just need to get a single Float data type value. In the PostgreSQL database, this field is of type real. I will be grateful)

`public Float getPlayerRatingValue(Integer idClub, Integer idPlayer) {
        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("idClub", idClub);
        parameters.addValue("idPlayer", idPlayer);
        parameters.addValue("zeroRating", ZERO_RATING);
        return namedParameterJdbcTemplate
                .queryForObject(
                        "SELECT rating_value " +
                                "FROM rating " +
                                "WHERE id_club = :idClub AND id_player = :idPlayer",
                        parameters,
                        new BeanPropertyRowMapper<>(Float.class)
                );`

Solution

  • NamedParameterJdbcTemplate has a special method for single row/column queries.

    So you can just pass a Float.class as the third parameter:

    return namedParameterJdbcTemplate
            .queryForObject(
                    "SELECT rating_value " +
                            "FROM rating " +
                            "WHERE id_club = :idClub AND id_player = :idPlayer",
                    parameters,
                    Float.class
            );
    

    Another quick example:

    MapSqlParameterSource parameterSource = new MapSqlParameterSource();
    Float f = jdbcTemplate.queryForObject("SELECT CAST(1 AS REAL)", parameterSource, Float.class);
    System.out.println(f);