2012-11-12 18 views
8

Các phương thức cơ sở dữ liệu trong Spring JDBC chấp nhận một nguồn tham số đơn. Ví dụ -Làm cách nào để kết hợp nhiều nguồn tham số trong Spring JDBC?

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

Có thể kết hợp nhiều nguồn tham số với nhau không? Ví dụ, giả sử tôi có một bean Order -

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

Tôi muốn lưu đậu này với một số lĩnh vực khác như recordModificationTimeaccessLevel.

Nếu tôi sử dụng MapSqlParameterSource cho các trường bổ sung tồn tại bên ngoài bean, tôi không thể sử dụng BeanPropertySqlParameterSource vì phương thức này chỉ chấp nhận một nguồn tham số. Có phải sử dụng MapSqlParameterSource cho tất cả dữ liệu của tôi có nghĩa là tôi phải tự giải nén tất cả các thuộc tính bean, đó là rất nhiều công việc.

Cách tốt nhất để giải quyết vấn đề này là gì?

Trả lời

12

Bạn có thể mở rộng AbstractSqlParameterSource và tổng hợp cả hai BeanProperty và Bản đồ phiên bản:

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

Và bây giờ sử dụng nó như thế này:

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

jdbcTemplate.update(sql, mySource); 
+0

Cảm ơn @dei, thay đổi kiểu trả về trên getValue. – mrembisz