Spring----学习(19)---在 JDBC 模板中使用具名参数

SQL 语句中使用具名参数时, 可以在一个 Map 中提供参数值, 参数名为键

也可以使用 SqlParameterSource 参数

批量更新时可以提供 Map SqlParameterSource 的数组

 spring bean配文件配置 NamedParameterJdbcTem

<!-- 配置NamedParameterJdbcTem,该对象可以使用具名参数,其没有无参数的构造器,所以必须为期构造器指定参数 -->
<bean id="NamedParameterJdbcTemplate"
      class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
      <constructor-arg ref="dataSource"></constructor-arg>
</bean>

 在使用具名参数进行对数据表更新的时候,可以实现传入一个Javabean对象来更新数据库表。

/**
 *使用救具名参数,可以使用update(String sql, SqlParameterSource paramSource)方法
 * 进行update操作。
 * 1.SQL语句中的具名参数和类的属性名必须保持一致。
 * 2.使用SqlParameterSource接口的BeanPropertySqlParameterSource实现类来实传入一个类实例。
 */
@Test
public void testNamedParameterJdbcTemplate(){
	String sql = "INSERT INTO GG_DEPARTMENT(ID,NAME) VALUES (:id,:name)";

	Emmploy emmploy = new Emmploy();
	emmploy.setId(284);
	emmploy.setName("oooooo");
	SqlParameterSource  paramSource = new BeanPropertySqlParameterSource(emmploy);

	namedParameterJdbcTemplate.update(sql, paramSource);
}

猜你喜欢

转载自blog.csdn.net/lsh15846393847/article/details/89403050