1. 程式人生 > >JDBC插入資料,更新資料,使用NamedParameterJdbcTemplate物件直接操作javaBean

JDBC插入資料,更新資料,使用NamedParameterJdbcTemplate物件直接操作javaBean

原來如此簡單:

DButil:

public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {

if (nam == null) {
            synchronized(DBUtil.class){  
        if (nam==null) {
        //呼叫NamedParameterJdbcTemplate都為update操作,資料來源必須為主庫
        nam = new NamedParameterJdbcTemplate(masterDBDataSource);
                } 
            }  
}
return nam;
}

Dao:

@Autowired
private DBUtil dbUtil;

public int add(ProviderInfoEntity providerInfoEntity) throws DataAccessException, UnsupportedEncodingException {
String insertsql =
"insert into RM_ProviderInfo (ProviderCode, ProviderName, ServiceCode, " +
"ServiceName, ResidueDegree, ExpireDate, Priority, Status, LastUpdateID, LastUpdateDate)"
+ " values (:ProviderCode, :ProviderName, :ServiceCode, :ServiceName, :ResidueDegree, :ExpireDate, :Priority, :Status, :LastUpdateID, :LastUpdateDate)";


SqlParameterSource sps = new BeanPropertySqlParameterSource(providerInfoEntity); 
return dbUtil.getNamedParameterJdbcTemplate().update(insertsql, sps);
 

}

結束

另外,沒有主從配置的資料庫,請參考下面程式碼:更簡潔

public int add(Entity entity) throws DataAccessException, UnsupportedEncodingException {


String insertsql =
"insert into RM_ProviderInfo (ProviderCode, ProviderName, ServiceCode, ServiceName, ResidueDegree, ExpireDate, Priority, Status, LastUpdateID, LastUpdateDate) values (:ProviderCode, :ProviderName, :ServiceCode, :ServiceName, :ResidueDegree, :ExpireDate, :Priority, :Status, :LastUpdateID, :LastUpdateDate)";

SqlParameterSource sps = new BeanPropertySqlParameterSource(entity); 

//下面的dataSource可從JdbcTemplate物件中獲取得到

NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(dataSource);

return npjt.update(insertsql, sps);

}