I have this piece of example code:
public Post findById(Long id) {
String sql = "select id, title, text from post where id = ?";
return template.queryForObject(sql, new Object[] {id}, getPostRowMapper());
}
I don't understand what the new Object[] {id}
is doing here
When you have a sql statement with a variable in it (the question mark sign), then you need to supply the variables that will be placed into that statement where the question marks are.
new Object[] {id}
tells us which variables should be put in places where the question marks are.
new Object[] {}
creates an empty array of objects. new Object[] {id}
creates an array of objects with one item in it - the Long id
, which is the function parameter.
So, let's say id is equal to 1. In that case, the question mark
where id = ?
Will be replaced with 1
where id = 1