Spring的JdbcTemplate是一个对JDBC的模板封装它提供了一套JDBC的模板能让我们写持久层代码时减少多余的代码简化JDBC代码使代码看起来更简洁。在介绍Spring的JdbcTemplate使用方法之前我们先来讨论一个问题以下这是一段常见的往数据库写入数据的JDBC代码public int jdbcInsert(Student student) throws SQLException { Connection connection null; try { connection dataSource.getConnection(); String sql INSERT INTO student(sname,age,sex,address) VALUES (?,?,?,?); PreparedStatement preparedStatement connection.prepareStatement(sql); preparedStatement.setString(1, student.getName()); preparedStatement.setInt(2, student.getAge()); preparedStatement.setString(3, student.getSex()); preparedStatement.setString(4, student.getAddress()); return preparedStatement.executeUpdate(); } finally { connection.close(); } } public int jdbcUpdate(Student student) throws SQLException { Connection connection null; try { connection dataSource.getConnection(); String sql UPDATE student SET sname?,age?,sex?,address?; PreparedStatement preparedStatement connection.prepareStatement(sql); preparedStatement.setString(1, student.getName()); preparedStatement.setInt(2, student.getAge()); preparedStatement.setString(3, student.getSex()); preparedStatement.setString(4, student.getAddress()); return preparedStatement.executeUpdate(); } finally { connection.close(); } }从如上的代码中可以看到两个方法中基本99%的代码都是重复的除了sql语句之外都是重复的代码重复的代码就是坏味道会让我们的产生大量的冗余代码不易于维护和修改而且写起来还累。所以Spring提供的JdbcTemplate正是用来解决这个问题的其实Spring的JDBCTemplate有点像DBUtils但是有时候还没有DBUitls好用。这里来学习一下使用Spring的JdbcTemplate来玩一下CRUD毕竟JdbcTemplate在实际开发中一般不会使用通常都是使用Mybatis、Hibernate等成熟、优秀的数据持久层框架不过还是得知道Spring有一个这样的jdbc模板类第一步需要在pom.xml增加jar依赖支持dependencygroupIdorg.springframework/groupIdartifactIdspring-jdbc/artifactIdversion5.3.8/version/dependency第二步在resources目录下新建一个spring.xml配置文件?xml version1.0 encodingUTF-8?beansxmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdcontext:annotation-config/context:annotation-configcontext:component-scanbase-packagecom.yh/!-- 1.设置外部文件方式;--context:property-placeholderlocationclasspath:jdbc.properties/!-- 设置dataSource--!-- bean iddataSource classorg.springframework.jdbc.datasource.DriverManagerDataSource property namedriverClassName valuecom.mysql.cj.jdbc.Driver/ property nameurl valuejdbc:mysql://localhost:3306/hr/ property nameusername valueroot/ property namepassword valueroot/ /bean--!-- druid方式--beaniddataSourceclasscom.alibaba.druid.pool.DruidDataSourcepropertynamedriverClassNamevalue${jdbc.driverClassName}/propertynameurlvalue${jdbc.url}/propertynameusernamevalue${jdbc.username}/propertynamepasswordvalue${jdbc.password}//bean!-- 针对JdbcTemplate的设置--beanidjdbcTemplateclassorg.springframework.jdbc.core.JdbcTemplatepropertynamedataSourcerefdataSource//bean/beans注意看这里设置了JdbcTemplate的的beanDataSource的bean。3.在resources下创建properties文件jdbc.driverClassNamecom.mysql.cj.jdbc.Driver jdbc.urljdbc:mysql://localhost:3306/hr jdbc.usernameroot jdbc.passwordroot4.在srcmain下创建package包。5.在dao包和dao下的子包impl下创建接口和实现类publicinterfaceUserDao{voidaddUser(Useruser);ListUserselectAllUsers();}RepositorypublicclassUserDaoImplimplementsUserDao{//注意这里把原来的jdbc,给封装一次使用JdbcTemplateAutowiredJdbcTemplatejdbcTemplate;publicvoidsetJdbcTemplate(JdbcTemplatejdbcTemplate){this.jdbcTemplatejdbcTemplate;}publicvoidaddUser(Useruser){//实现相应的add操作jdbc...// jdbcTemplate.execute((user.getId(),user.getUserName()));Stringsqlinsert user(id,user_name)values(?,?);jdbcTemplate.update(sql,user.getId(),user.getUserName());}publicListUserselectAllUsers(){Stringsqlselect * from user;returnjdbcTemplate.query(sql,newBeanPropertyRowMapperUser(User.class));}} java6.在业务层创建UserService接口和下面的子包创建UserServiceImpl实现类publicinterfaceUserService{voidaddUser(Useruser);ListUserselectAllUsers();}ServicepublicclassUserServiceImplimplementsUserService{AutowiredUserDaouserDao;publicvoidaddUser(Useruser){userDao.addUser(user);}publicListUserselectAllUsers(){returnuserDao.selectAllUsers();}}7.实体类Component// DataNoArgsConstructorAllArgsConstructorpublicclassUser{privateIntegerid;publicIntegergetId(){returnid;}publicvoidsetId(Integerid){this.idid;}publicStringgetUserName(){returnuserName;}publicvoidsetUserName(StringuserName){this.userNameuserName;}privateStringuserName;}