直接上代码
public class User { private Long id; private String username; private String password; }beans.xml
<context:property-placeholder location="classpath:settings.properties" /><!-- 查看对应的配置 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性 url、user、password --> <property name="url" value="${db_url}" /> <property name="username" value="${db_username}" /> <property name="password" value="${db_password}" /> <property name="driverClassName" value="${db_className}" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1" /> <property name="minIdle" value="1" /> <property name="maxActive" value="20" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="60000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x'" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 --> <property name="filters" value="stat" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean>testClass
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:beans.xml"}) public class TestJdbcTemplate { @Resource private JdbcTemplate jdbcTemplate; @Test public void testQuery() { String sql = "select id, username, password from t_user"; List<User> users = jdbcTemplate.query(sql, new RowMapper<User>() { @Override public User mapRow(ResultSet rs, int rowNum) throws SQLException { User u = new User(); u.setId(rs.getLong(1)); u.setUsername(rs.getString(2)); u.setPassword(rs.getString(3)); return u; } }); System.out.println(Arrays.deepToString(users.toArray())); } //...略 }之后补上示例的dao