<!-- 配置 C3P0 數據源 -->java
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean>
<!-- 配置 NamedParameterJdbcTemplate, 該對象可使用具名參數, 其沒有無參數的構造器, 因此必須爲其構造器指定參數 -->spring
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <constructor-arg ref="dataSource"></constructor-arg> </bean>
public class JDBCTest { private ApplicationContext ctx = null; private JdbcTemplate jdbcTemplate; private EmployeeDao employeeDao; private DepartmentDao departmentDao; private NamedParameterJdbcTemplate namedParameterJdbcTemplate; { ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); namedParameterJdbcTemplate = ctx.getBean(NamedParameterJdbcTemplate.class); } /** * 使用具名參數時, 可使用 update(String sql, SqlParameterSource paramSource) 方法進行更新操做 * 1. SQL 語句中的參數名和類的屬性一致! * 2. 使用 SqlParameterSource 的 BeanPropertySqlParameterSource 實現類做爲參數. */ @Test public void testNamedParameterJdbcTemplate2(){ String sql = "INSERT INTO employees(last_name, email, dept_id) " + "VALUES(:lastName,:email,:dpetId)"; Employee employee = new Employee(); employee.setLastName("XYZ"); employee.setEmail("xyz@sina.com"); employee.setDpetId(3); SqlParameterSource paramSource = new BeanPropertySqlParameterSource(employee); namedParameterJdbcTemplate.update(sql, paramSource); } /** * 能夠爲參數起名字. * 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", "ff@atguigu.com"); paramMap.put("deptid", 2); namedParameterJdbcTemplate.update(sql, paramMap); } }