14

Spring JDBC 中的数据库方法接受单个参数源。例如 -

int org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(String sql, SqlParameterSource paramSource) throws DataAccessException

是否可以将多个参数源组合在一起?例如,假设我有一个豆子Order——

class Order {
int id;
float price;
int customerId;
Date date;
//Lots of other fields
}

我想用一些额外的字段来保存这个 bean,比如recordModificationTimeaccessLevel

如果我使用MapSqlParameterSource这些存在于 bean 之外的额外字段,我将无法使用BeanPropertySqlParameterSource,因为该方法只接受一个参数源。必须使用MapSqlParameterSource我的所有数据意味着我必须手动提取所有 bean 属性,这是很多工作。

处理这个问题的最佳方法是什么?

4

1 回答 1

21

您可以扩展AbstractSqlParameterSource和聚合 BeanProperty 和 Map 版本:

public class CombinedSqlParameterSource extends AbstractSqlParameterSource {
  private MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();
  private BeanPropertySqlParameterSource beanPropertySqlParameterSource;

  public CombinedSqlParameterSource(Object object) {
    this.beanPropertySqlParameterSource = new BeanPropertySqlParameterSource(object);
  }

  public void addValue(String paramName, Object value) {
    mapSqlParameterSource.addValue(paramName, value);
  }

  @Override
  public boolean hasValue(String paramName) {
    return beanPropertySqlParameterSource.hasValue(paramName) || mapSqlParameterSource.hasValue(paramName);
  }

  @Override
  public Object getValue(String paramName) {
    return beanPropertySqlParameterSource.hasValue(paramName) ? beanPropertySqlParameterSource.getValue(paramName) : mapSqlParameterSource.getValue(paramName);
  }

  @Override
  public int getSqlType(String paramName) {
    return beanPropertySqlParameterSource.hasValue(paramName) ? beanPropertySqlParameterSource.getSqlType(paramName) : mapSqlParameterSource.getSqlType(paramName);
  }
}

现在像这样使用它:

CombinedSqlParameterSource mySource = new CombinedSqlParameterSource(myOrder);
mySource.addValue("recordModificationTime", time);
mySource.addValue("accessLevel", level);

jdbcTemplate.update(sql, mySource);
于 2012-11-12T09:37:44.320 回答