为了解决这个问题,可以使用“命名参数”,SQL参数是由一个冒号开始后续定义的名称,而不是位置。在另外的,命名参数只是在SimpleJdbcTemplate类和NamedParameterJdbcTemplate支持。
//insert with named parameter public void insertNamedParameter(Customer customer){ String sql = "INSERT INTO CUSTOMER " + "(CUST_ID, NAME, AGE) VALUES (:custId, :name, :age)"; Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("custId", customer.getCustId()); parameters.put("name", customer.getName()); parameters.put("age", customer.getAge()); getSimpleJdbcTemplate().update(sql, parameters); }
public void insertBatchNamedParameter(final List<Customer> customers){ String sql = "INSERT INTO CUSTOMER " + "(CUST_ID, NAME, AGE) VALUES (:custId, :name, :age)"; List<SqlParameterSource> parameters = new ArrayList<SqlParameterSource>(); for (Customer cust : customers) { parameters.add(new BeanPropertySqlParameterSource(cust)); } getSimpleJdbcTemplate().batchUpdate(sql, parameters.toArray(new SqlParameterSource[0])); }
public void insertBatchNamedParameter2(final List<Customer> customers){ SqlParameterSource[] params = SqlParameterSourceUtils.createBatch(customers.toArray()); getSimpleJdbcTemplate().batchUpdate( "INSERT INTO CUSTOMER (CUST_ID, NAME, AGE) VALUES (:custId, :name, :age)", params); }