1.定义
JdbcTemplate是将spring与jdbc进行了整合,可以简化数据库操作,相比Hibernate、Mybatis感觉配置少很多,用起来有点像springboot的JPA,但是会比它臃肿一些。
2.应用
2.1 配置
采用数据库连接池
<bean id="dataSourceMeta" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driverClassName}" />
<property name="jdbcUrl" value="${url}" />
<property name="user" value="${user_name}" />
<property name="password" value="${password}" />
<!-- 初始化连接大小 -->
<property name="initialPoolSize" value="${initialSize}"></property>
<property name="maxPoolSize" value="${maxActive}"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" scope="prototype">
<property name="dataSource" ref="dataSource"></property>
</bean>
这样在类中就可以直接@Autowired注入这个对象,注意该类必须也通过注解方式new
2.2 使用
1)查询
String sql = "select count(*) ncount from t where 1=1 and t.managerid=" + managerid;
int ncount = jdbcTemplate.queryForObject(sql, Integer.class);
queryForObject进行数据库查询无数据时会抛出如下异常提示息
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0 或者 org.springframework.dao.IncorrectResultSizeDataAccessException: Incorrect result size: expected 1, actual 2
为了避免出现以上的异常,最好还是使用query查出list,取第一个元素就行
List<String> taaccountids = jdbcTemplate.query(sb.toString(), new RowMapper<String>() {
@Override
public String mapRow(ResultSet resultSet, int i) throws SQLException {
return resultSet.getString("taaccountid");
}
});
2)批量操作
jdbcTemplate.batchUpdate(delSql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
Customer cust= CustomerList.get(i);
preparedStatement.setString(1, cust.getTaaccountid());
preparedStatement.setString(2, "0000");
}
@Override
public int getBatchSize() {
return custRiskViewParamList.size();
}
});
这里会有个问题,例如当我CustomerList比较大,有5W条,分批次提交就需要自己用for循环,因为batchUpdate它的方法getBatchSize()默认就是提交整个list的大小。所以我们可以截取list,每一万条提交一下,不然等5W一批次会存在内存溢出等问题。
3.安全性
jdbcTemplate是线程安全的,在多线程环境下都可以共用,哪怕多个线程同时操作同一张表