简述
JdbcTemplate是Spring JDBC的核心类,Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中,借助该类提供的方法可以很方便的实现数据的增删改查。
配置
在xml文件中写入代码:
<context:component-scan base-package="com.jd"></context:component-scan>
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" lazy-init="false" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
上面dataSource配置代码可以使用下面三种方式中的一种代替:
<!-- 第一种方式 -->
<bean class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource"></bean>
<!-- 第二种方式 -->
<bean class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource="#{dataSource}"></bean>
<!-- 第三种方式 -->
<bean class="org.springframework.jdbc.core.JdbcTemplate" autowire="byName"></bean>
常用方法:
修改:
int update(final String sql):数据修改,返回受影响的行数。
int update(String sql, Object… args) throws DataAccessException:数据修改,返回受影响的行数,该方法可以规避SQL注入,例子如下:
piblic boolean delete(String id){
String sql = "delete from user where user_id =?";
return jdbcTemplate.update(sql,id)>0;
}
int[] batchUpdate(final String… sql):批量更新,返回每条DML语句执行后受影响行数组成的数组。
查询:
T queryForObject(String sql, Class requiredType) throws DataAccessException:根据SQL语句返回某列的值,其中requiredType用于指定该列的数据类型。
T queryForObject(String sql, Class requiredType, Object… args) throws DataAccessException:同上,该方法可以规避SQL注入。
T queryForObject(String sql, RowMapper rowMapper) throws DataAccessException:返回SQL语句查出的某条数据,该数据的数据类型由RowMapper接口实现类决定。
T queryForObject(String sql, RowMapper rowMapper, Object… args) throws DataAccessException:同上,该方法可以规避SQL注入,例子如下:
List query(String sql, RowMapper rowMapper) throws DataAccessException:返回SQL语句查出的所有数据组成的List集合,集合中元素数据类型由RowMapper接口实现类决定
List query(String sql, RowMapper rowMapper, Object… args) throws DataAccessException:同上,该方法可以规避SQL注入:
T query(final String sql, final ResultSetExtractor rse) throws DataAccessException:返回SQL语句查出数据组成的结果,该结果数据类型由ResultSetExtractor接口实现类决定
T query(String sql, ResultSetExtractor rse, Object… args) throws DataAccessException:同上,该方法可以规避SQL注入,例子如下:
public List<UserInfo> selectAll(){
String sql = "select user_id,user_name,user_passwd from user";
return jdbcTemplate.query(sql, (ResultSet rs)->{
List<UserInfo> list = new ArrayList<>();
while(rs.next()) {
UserInfo userInfo = new UserInfo();
userInfo.setUserId(rs.getInt("user_id"));
userInfo.setUserName(rs.getString("user_name"));
userInfo.setUserPasswd(rs.getString("user_passwd"));
list.add(userInfo);
}
return list;
});
}