I am using Spring's SimpleJdbcInsert class to create entities - eg:
final SimpleJdbcInsert insert = new SimpleJdbcInsert(dataSource).withTableName("abc");
insert.execute(new BeanPropertySqlParameterSource(abc));
Is there some equivalent of this class for doing updates? As an example, something like the below would be a convenient interface, assuming we are dealing with a single column primary key:
final SimpleJdbcUpdate update = new SimpleJdbcUpdate(dataSource).withTableName("abc").withIdColumn("abcId");
update.execute(new BeanPropertySqlParameterSource(abc));
Does Spring provide this functionality out-of-the-box somewhere?
Thanks Jay
For any future readers - I came up with a convenience function using reflection;
Works for simple pojos:
public void dao_update(NamedParameterJdbcTemplate database, String table, Object pojo, String[] keys) {
StringBuilder sqlBuilder = new StringBuilder("UPDATE ");
sqlBuilder.append(table);
sqlBuilder.append(" SET ");
boolean first = true;
for (Field field : pojo.getClass().getDeclaredFields()) {
if (!first) {
sqlBuilder.append(",");
}
first = false;
sqlBuilder.append(field.getName());
sqlBuilder.append(" = :");
sqlBuilder.append(field.getName());
}
first = true;
for (String key : keys) {
if (first) {
sqlBuilder.append(" WHERE ");
} else {
sqlBuilder.append(" AND ");
}
first = false;
sqlBuilder.append(key);
sqlBuilder.append("= :");
sqlBuilder.append(key);
}
database.getJdbcOperations().update(sqlBuilder.toString(), new BeanPropertySqlParameterSource(pojo));
}
Example usage:
dao_update(database, "employee", my_employee, "id");
Generates:
UPDATE employee SET id = :id, name = :name, salary = :salary WHERE id = :id
There is an issue in the Spring JIRA about the lack of a SimpleJdbcUpdate
class: https://jira.springsource.org/browse/SPR-4691. You might want to upvote it there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With