Spring Named Parameters examples in SimpleJdbcTemplate
2015-08-23 14:56
387 查看
In
To fix it, you can use “
See following three examples to use named parameters in Spring.
JdbcTemplate, SQL parameters are represented by a special placeholder “
?” symbol and bind it by position. The problem is whenever the order of parameter is changed, you have to change the parameters bindings as well, it’s error prone and cumbersome to maintain it.
To fix it, you can use “
Named Parameter“, whereas SQL parameters are defined by a starting colon follow by a name, rather than by position. In additional, the named parameters are only support in
SimpleJdbcTemplateand
NamedParameterJdbcTemplate.
See following three examples to use named parameters in Spring.
Example 1
Example to show you how to use named parameters in a single insert statement.//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); }
Example 2
Examples to show how to use named parameters in a batch operation statement.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])); }
Example 3
Another examples to use named parameters in a batch operation statement.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); }
相关文章推荐
- Spring SimpleJdbcTemplate batchUpdate() example
- Spring SimpleJdbcTemplate Querying examples
- Spring JdbcTemplate batchUpdate() example
- Spring JdbcTemplate Querying examples
- java学习个人笔记---Java内存管理之java对象内存中的状态
- java1.8环境配置(win8)
- Java实现简单的二叉树
- Spring + JdbcTemplate + JdbcDaoSupport examples
- Spring Boot——开发新一代Spring应用
- 从零开始学Java之线程详解(1):原理、创建
- Spring Boot——开发新一代Spring应用
- Spring Boot——开发新一代Spring应用
- Spring Boot——开发新一代Spring应用
- Java之旅hibernate(4)——hibernate入门示例
- 去哪网实习总结:JavaWeb中文传参乱码问题的解决(JavaWeb)
- 使用Java中间MessageDigest该文本MD5加密(Java中间MD5样品加密算法演示)
- 去哪网实习总结:JavaWeb配置404页面(JavaWeb)
- java-多线程-线程池
- Java之旅hibernate(3)——第一个hibernate的例子
- Struts2 标签库讲解