2012-11-12 8 views
8

I metodi del database in Spring JDBC accettano una singola origine parametro. Ad esempio -Come combinare più fonti di parametri in Spring JDBC?

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

È possibile combinare più fonti di parametri insieme? Ad esempio, supponiamo di avere un fagiolo Order -

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

voglio salvare questa fagioli con alcuni campi aggiuntivi come recordModificationTime e accessLevel.

Se utilizzo per questi campi aggiuntivi che esistono all'esterno del bean, non è possibile utilizzare BeanPropertySqlParameterSource perché il metodo accetta solo un'origine dei parametri. Dover usare MapSqlParameterSource per tutti i miei dati significa che devo estrarre manualmente tutte le proprietà del bean, il che è molto lavoro.

Qual è il modo migliore per affrontare questo problema?

risposta

12

È possibile estendere AbstractSqlParameterSource e aggregare entrambe le versioni BeanProperty e mappa:

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

E ora usare in questo modo:

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

jdbcTemplate.update(sql, mySource); 
+0

Grazie @dei, Tipo di ritorno cambiato sul getValue. – mrembisz