[英]How to combine multiple parameter sources in Spring JDBC?
Spring JDBC中的數據庫方法接受單個參數源。 例如 -
int org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(String sql, SqlParameterSource paramSource) throws DataAccessException
是否可以將多個參數源組合在一起? 例如,假設我有一個bean Order
-
class Order {
int id;
float price;
int customerId;
Date date;
//Lots of other fields
}
我想用一些其他字段保存這個bean,比如recordModificationTime
和accessLevel
。
如果我將MapSqlParameterSource
用於存在於bean之外的這些額外字段,我不能使用BeanPropertySqlParameterSource
因為該方法只接受一個參數源。 MapSqlParameterSource
為我的所有數據使用MapSqlParameterSource
意味着我必須手動提取所有bean屬性,這是很多工作。
處理這個問題的最佳方法是什么?
您可以擴展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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.