為了解決這個問題,可以使用「命名引數」,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); }