2012-11-12 3 views
8

Spring JDBC의 데이터베이스 메소드는 단일 매개 변수 소스를 허용합니다. 예 : -Spring JDBC에서 여러 매개 변수 소스를 결합하는 방법은 무엇입니까?

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

여러 매개 변수 원본을 함께 조합 할 수 있습니까? 내가 recordModificationTimeaccessLevel 같은 일부 추가 필드와 함께이 콩을 저장할

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

- 예를 들어, 나는 콩을 Order이 있다고 가정합니다.

빈 외부에있는 이러한 여분의 필드에 MapSqlParameterSource을 사용하는 경우 메서드가 하나의 매개 변수 원본 만 허용하기 때문에 BeanPropertySqlParameterSource을 사용할 수 없습니다. 모든 데이터에 MapSqlParameterSource을 사용해야한다는 것은 모든 bean 속성을 수동으로 추출해야한다는 것을 의미합니다. 이는 많은 작업입니다.

이 문제를 해결하는 가장 좋은 방법은 무엇입니까? 이처럼 사용 지금

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); 
    } 
} 

을 그리고 :

답변

12

당신은 AbstractSqlParameterSource를 확장하고 모두 BeanProperty와지도 버전을 집계 할 수

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

jdbcTemplate.update(sql, mySource); 
+0

감사 getValue에 @dei이 변경 반환 형식을. – mrembisz

관련 문제