Spring JDBC中具名参数的用法
- maven引入Spring jdbc
<dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.3.19</version></dependency>
- 在Spring配置中配置
<!-- dataSource配置 -> <bean id="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"destroy-method="close" p:driverClass="${jdbc.driverClassName}"p:jdbcUrl="${jdbc.url}" p:user="${jdbc.username}"p:password="${jdbc.password}" /><!-- 具名参数要用到的类 -> <bean id="namedParameterJdbcTemplate"class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"><constructor-arg ref="dataSource"></constructor-arg></bean>
- 使用
package testSpring;import java.util.HashMap; import java.util.Map;import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;import test.spring.model.User;public class TestSpring {@Testpublic void testUser() {ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");NamedParameterJdbcTemplate namedParameterJdbcTemplate=(NamedParameterJdbcTemplate) ac.getBean("namedParameterJdbcTemplate");String sql = "select * from User where id=:uid";Map<String,Object> paramMap= new HashMap<>();paramMap.put("uid", 1);RowMapper<User> rowMap = new BeanPropertyRowMapper<>(User.class);User user=(User) namedParameterJdbcTemplate.queryForObject(sql, paramMap, rowMap);System.out.println(user);} }