原来如此简单:
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);
}