I want only value from the column which is Integer type.
I have this code here as:
In Controller:
@GetMapping("/rating/{id}")
Rating findRating(@PathVariable Integer id) {
Optional<Rating> rating = runRepository.findRating(id);
System.out.println("rating is -------"+rating.get());
return rating.get();
}
In Repository:
public Optional<Rating> findRating(Integer id) {
return jdbcClient.sql
("select rating from movie where id = :id")
.param("id", id).query(Rating.class).optional();
}
The Output is:
rating is -------Rating[rating=9.0]
The problem with this code is that I will have to trim this value and then I can play around (calculating average etc) with my value 9.0, but I want to make it easier with code. Is there any option?
I tried the above snippet and I expect only the value rather than the column name and value.
3
Try this:
In Repository:
Changed the method findRating to return Optional. Used JdbcTemplate to directly map the result set to an integer value. The query method extracts the integer value from the result set and wraps it in an Optional.
public Optional<Integer> findRating(Integer id) {
String sql = "SELECT rating FROM movie WHERE id = ?";
return jdbcTemplate.query(sql, new Object[]{id}, rs -> {
if (rs.next()) {
return Optional.of(rs.getInt("rating"));
} else {
return Optional.empty();
}
});
}
In Controller:
Changed the return type of the findRating method to ResponseEntity. If a rating is found, it prints the rating and returns it wrapped in an HTTP 200 OK response. If no rating is found, it returns an HTTP 404 Not Found response.
@GetMapping("/rating/{id}")
public ResponseEntity<Integer> findRating(@PathVariable Integer id) {
Optional<Integer> rating = runRepository.findRating(id);
if (rating.isPresent()) {
System.out.println("rating is -------" + rating.get());
return new ResponseEntity<>(rating.get(), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
Doing this only the integer rating value is returned from the repository and handled cleanly in the Controller.