Updating an object
In this recipe, we will add a DAO method to update an existing row in the database with an object's fields.
How to do it…
Use an SQL update query and execute it using the update() method:
public void update(User user) {
String sql = "update user set first_name=?, age=? where id=?";
jdbcTemplate.update(sql, user.getFirstName(), user.getAge(), user.getId());
}There's more…
It's convenient to also have a save() method that will create the database row if it doesn't exist:
public void save(User user) {
if (user.getId() == null) {
add(user);
}
else {
update(user);
}
}