Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleJdbcInsert equivalent for update

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

like image 882
James Hargreaves Avatar asked May 23 '12 15:05

James Hargreaves


2 Answers

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

like image 190
nclord Avatar answered Oct 25 '22 16:10

nclord


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.

like image 38
P44T Avatar answered Oct 25 '22 14:10

P44T