NamedParameterJdbcTemplate with parameters and RowMapper
Create a row mapper that will map result of a query to a domain object.
class UserRowMapper implements RowMapper {
@Override
Object mapRow(ResultSet rs, int rowNum) throws SQLException {
return new User(firstName: rs.getString('first_name'))
}
}
Now we can give UserRowMapper to named JDBC template and it will map the result of the query into a new instance of User class.
NamedParameterJdbcTemplate namedJdbcTemplate = Grails.get(NamedParameterJdbcTemplate)
Map params = [id: 1]
UserRowMapper mapper = new UserRowMapper()
User usersY = namedJdbcTemplate.queryForObject("SELECT * FROM User WHERE id=:id", params, mapper)
layout.addComponent(new Label(usersY.firstName))
If you use for SQL string construction, there is a comfortable way to get as a map.
Use in case your domain model matches name of columns in a database table. Then you do not have to create mappers and data from your queries will automatically transfered to instance of a domain class.