接上一节:https://www.cnblogs.com/xiximayou/p/12167150.html。
在applicationContext.xml中配置namedParameterJdbcTemplate。
<!-- 配置 NamedParameterJdbcTemplate,该对象可以使用具名参数,其没有无参数的构造器,所以必须为其构造器指定参数 --> <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> constructor-arg ref="dataSource"></constructor-arg> </bean>
在JDBCTest.java中进行测试:
private ApplicationContext ctx = null; private JdbcTemplate jdbcTemplate; EmployeeDao employeeDao; DepartmentDao departmentDao; NamedParameterJdbcTemplate namedParameterJdbcTemplate; { ctx = new ClasspathXmlApplicationContext("applicationContext.xml"); jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate"); employeeDao = ctx.getBean(EmployeeDao.class); departmentDao = ctx.getBean(DepartmentDao.); namedParameterJdbcTemplate = ctx.getBean(NamedParameterJdbcTemplate.); } /** * 可以为参数起名字. * 1. 好处: 若有多个参数,则不用再去对应位置,直接对应参数名,便于维护 * 2. 缺点: 较为麻烦. */ @Test public void testNamedParameterJdbcTemplate(){ String sql = "INSERT INTO employees(last_name,email,dept_id) VALUES(:ln,:email,:deptid)"; Map<String,Object> paramMap = new HashMap<>(); paramMap.put("ln","FF"); paramMap.put("email","[email protected]"); paramMap.put("deptid",2); namedParameterJdbcTemplate.update(sql,paramMap); } * 使用具名参数时,可以使用 update(String sql,sqlParameterSource paramSource) 方法进行更新操作 * 1. sql 语句中的参数名和类的属性一致! * 2. 使用 sqlParameterSource 的 BeanPropertysqlParameterSource 实现类作为参数. testNamedParameterJdbcTemplate2(){ String sql = "INSERT INTO employees(last_name,dept_id) " + "VALUES(:lastName,:dpetId)"; Employee employee = new Employee(); employee.setLastName("XYZ"); employee.setEmail("[email protected]"); employee.setDpetId(3); sqlParameterSource paramSource = BeanPropertysqlParameterSource(employee); namedParameterJdbcTemplate.update(sql,paramSource); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。