一、简介

 Spring提供的一个操作数据库的技术JdbcTemplate,是对Jdbc的封装。语法风格非常接近DBUtils。
 JdbcTemplate可以直接操作数据库,加快效率,而且学这个JdbcTemplate也是为声明式事务做准备,毕竟要对数据库中的数据进行操纵!

JdbcTemplate中并没有提供一级缓存,以及类与类之间的关联关系!就像是spring提供的一个DBUtils。

Spring对数据库的操作使用JdbcTemplate来封装JDBC,结合Spring的注入特性可以很方便的实现对数据库的访问操作。使用JdbcTemplate可以像JDBC一样来编写数据库

的操作代码


二、优势


Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中。
Spring提供的JdbcTemplate对jdbc做了封装,大大简化了数据库的操作。找到Spring JdbcTemplate源码,可以看到如下方法:
  Connection con = DataSourceUtils.getConnection(getDataSource());
如果直接使用JDBC的话,需要我们加载数据库驱动、创建连接、释放连接、异常处理等一系列的动作;繁琐且代码看起来不直观。
此外,Spring提供的JdbcTempate能直接数据对象映射成实体类,不再需要获取ResultSet去获取值/赋值等操作,提高开发效率;
  如下:return (User) jdbcTemplate.queryForObject("select * from tb_test1 where id = 100", User.class)

三、.配置环境

①导入jar包
  [1]IOC容器需要的jar包

commons-logging-1.1.3.jar
spring-aop-4.0.0.RELEASE.jar //注解会使用到的包
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
View Code

  [2]MySQL驱动、C3P0jar包

c3p0-0.9.1.2.jar
mysql-connector-java-5.1.37-bin.jar
View Code

 [3]JdbcTemplate需要的jar包

spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
View Code


②在IOC容器中配置数据源

<!-- 加载properties文件中 信息 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置数据源 -->
<bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.passowrd}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="driverClass" value="${jdbc.driver}"></property>
</bean>
View Code

其中jdbc.properties文件内容:

jdbc.user=root
jdbc.passowrd=123456
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.driver=com.mysql.jdbc.Driver
View Code

③在IOC容器中配置JdbcTemplate对象的bean,并将数据源对象装配到JdbcTemplate对象中.

<!-- 配置JdbcTemplate对应的bean, 并装配dataSource数据源属性-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="comboPooledDataSource"></property>
</bean>
View Code

四、实验用例

实验1:测试数据源
    @Test
    public void test() throws SQLException {
        ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource bean = ioc.getBean(DataSource.class);
        System.out.println(bean.getConnection());
    }

实验2:将emp_id=5的记录的salary字段更新为1300.00【更新操作】
    public class TestDataSource {
        private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
        private JdbcTemplate template=ioc.getBean(JdbcTemplate.class);

        @Test
        public void test01(){
            //实验2:将emp_id=5的记录的salary字段更新为1300.00
            String sql = "UPDATE employee SET salary = ? WHERE emp_id = ?";
            template.update(sql, 1300,5);//第一个是sql语句,后面的按着顺序传入参数即可,这个update方法是接收的可变参数!
        }
    }
    从上述实验中就可以看到,该操作不用我们自己再去获取数据库连接信息了,而是直接传递sql语句及其参数!
    
    
实验3:批量插入
        public class TestDataSource {
                private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
                private JdbcTemplate template=ioc.getBean(JdbcTemplate.class);
                @Test
                public void testBatch(){
                    String sql="INSERT INTO employee(`emp_name`,`salary`) VALUES(?,?)";
                    //执行sql语句需要传递的参数
            //        Object[][] params = new Object[3][2];
            //        params[0] = new Object[]{"Tom2015",1000};
            //        params[1] = new Object[]{"Tom2016",2000};
            //        params[2] = new Object[]{"Tom2017",3000};
            //        
                    List<Object[]> list = new ArrayList<Object[]>();
                    list.add(new Object[]{"Tom2015",1000});
                    list.add(new Object[]{"Tom2016",2000});
                    list.add(new Object[]{"Tom2017",3000});
                    
                    template.batchUpdate(sql, list);
                }
        }
        
        

实验4:查询emp_id=5的数据库记录,封装为一个Java对象返回
       分析:封装为一个对象返回的话,首先我们需要有一个与数据表对应的实体类!
       
        public class TestDataSource {
            private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
            private JdbcTemplate template=ioc.getBean(JdbcTemplate.class);
            
            @Test
            public void test01(){
                //需要注意的是:sql语句中的别名要与对应实体类的属性名保持一致!
                String sql = "SELECT emp_id AS empId,emp_name AS empName,salary FROM employee WHERE emp_id=?";
                
                //RowMapper是一个接口,这里我们使用其子类
                RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class);
                //最后一个参数是可变参数,用于向sql语句中依次传递参数!
                Employee employee = template.queryForObject(sql, rowMapper, 5);
                System.out.println(employee);
            }
        }

实验5:查询salary>4000的数据库记录,封装为List集合返回
        public class TestDataSource {
            private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
            private JdbcTemplate template=ioc.getBean(JdbcTemplate.class);
            
            @Test
            public void test01(){
                //需要注意的是:sql语句中的别名要与对应实体类的属性名保持一致!
                String sql = "SELECT emp_id AS empId,emp_name AS empName,salary FROM employee WHERE salary > ?";
                
                //RowMapper是一个接口,这里我们使用其子类
                RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class);
                //该query方法查询出来的是一个list列表,query方法的最后一个参数是可变参数!
                List<Employee> list = template.query(sql, rowMapper, 4000);
                
                for (Employee employee : list) {
                    System.out.println(employee);
                }
            }
        }
        
        //从上面可以看出,查询结果是一个实体还是一个list列表是靠template对象的不同方法实现的!
        
    
实验6:查询最大salary
    public class TestDataSource {
        private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
        private JdbcTemplate template=ioc.getBean(JdbcTemplate.class);
        
        @Test
        public void test01(){
            String sql = "SELECT MAX(salary) FROM employee";
            //需要指定返回值的类型,而且类型必须是包装类型
            Double maxSalary = template.queryForObject(sql, Double.class);
            System.out.println(maxSalary);
        }
    }

实验7:使用带有具名参数的SQL语句插入一条员工记录,并以Map形式传入参数值

        具名参数:是指基于名称的,前面我们使用的都是用?作为占位符,然后是使用基于位置的!
        
        如果要使用具名参数的sql语句就必须在spring配置文件中配置NamedParameterJdbcTemplate这个模板类,而不能使用
        
        原来的JdbcTemplate,因为JdbcTemplate不能完成这样的任务!
            
                <!-- 加载properties文件中 信息 -->
            <context:property-placeholder location="classpath:jdbc.properties"/>
            <!-- 配置数据源 -->
            <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                <property name="user" value="${jdbc.user}"></property>
                <property name="password" value="${jdbc.passowrd}"></property>
                <property name="jdbcUrl" value="${jdbc.url}"></property>
                <property name="driverClass" value="${jdbc.driver}"></property>
            </bean>
            
            <!-- 配置JdbcTemplate对应的bean, 并装配dataSource数据源属性-->
            <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
                <property name="dataSource" ref="comboPooledDataSource"></property>
            </bean>
            <!-- 为了执行带有具名参数的SQL语句,需要配置NamedParameterJdbcTemplate -->
            <!-- 该NamedParameterJdbcTemplate类没有无参构造器,需要传入JdbcTemplate对象或者数据源对象[DataSource] -->
            <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
                <!-- 不能使用property标签配置哦 -->
                <constructor-arg ref="jdbcTemplate"></constructor-arg>
            </bean>
    
        public class TestDataSource {
            private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
            private NamedParameterJdbcTemplate namedJdbcTemplate = ioc.getBean(NamedParameterJdbcTemplate.class);
            
            @Test
            public void test01(){
                String sql="INSERT INTO employee(`emp_name`,`salary`) VALUES(:paramName,:paramSalary)";
                Map<String,Object> paramMap = new HashMap<String,Object>();
                paramMap.put("paramName","张学友" );
                paramMap.put("paramSalary",1000);
                
                namedJdbcTemplate.update(sql, paramMap);
            }
        }
                

实验8:重复实验7,以SqlParameterSource形式传入参数值

        public class TestDataSource {
            private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
            private NamedParameterJdbcTemplate namedJdbcTemplate = ioc.getBean(NamedParameterJdbcTemplate.class);
            
            @Test
            public void test01(){
                String sql="INSERT INTO employee(`emp_name`,`salary`) VALUES(:empName,:salary)";
                //该BeanPropertySqlParameterSource类构造器需要一个对象参数,该对象参数是一个封装了sql语句参数的对象!
                //此时要求对象的属性名要和sql中的参数名保持一致!这里我们使用Employee对象来完成
                Employee employee= new Employee(null, "郭富城", 1500);
                //以实体对象的形式封装具名参数和值
                SqlParameterSource source = new BeanPropertySqlParameterSource(employee);
                
                namedJdbcTemplate.update(sql, source);
            }
        }

        
实验9:创建JdbcTemplateDao,自动装配JdbcTemplate对象
           1.创建dao类:
               @Repository
                public class JdbcTemplateDao {
                    @Autowired
                    private JdbcTemplate jdbcTemplate;
                    
                    public void update(String sql,Object ...args){
                        jdbcTemplate.update(sql, args);
                    }
                }
           2.配置spring的配置文件
                <!-- 配置扫描的包 -->
                <context:component-scan base-package="com.neuedu.dao"></context:component-scan>
                <!-- 加载properties文件中 信息 -->
                <context:property-placeholder location="classpath:jdbc.properties"/>
                <!-- 配置数据源 -->
                <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                    <property name="user" value="${jdbc.user}"></property>
                    <property name="password" value="${jdbc.passowrd}"></property>
                    <property name="jdbcUrl" value="${jdbc.url}"></property>
                    <property name="driverClass" value="${jdbc.driver}"></property>
                </bean>
                
                <!-- 配置JdbcTemplate对应的bean, 并装配dataSource数据源属性-->
                <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
                    <property name="dataSource" ref="comboPooledDataSource"></property>
                </bean>
                
             3.测试该dao  
                 public class TestDataSource {
                    private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
                    private NamedParameterJdbcTemplate namedJdbcTemplate = ioc.getBean(NamedParameterJdbcTemplate.class);
                    
                    @Test
                    public void test01(){
                        JdbcTemplateDao dao = ioc.getBean(JdbcTemplateDao.class);
                        String sql = "INSERT INTO employee(`emp_name`,`salary`) VALUES(?,?)";
                        dao.update(sql, "比尔盖茨",10000000);
                    }
                }
View Code