七.JdbcTemplate

​ 概念:Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中。目的是使JDBC更加易于使用。JdbcTemplate是Spring的一部分。 JdbcTemplate处理了资源的建立和释放。

作用:

1.不需要管理连接

2.不需要设置参数

3.可以返回实体类

常用方法:

  • execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
  • update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;
  • query方法及queryForXXX方法:用于执行查询相关语句;
  • call方法: 用于执行存储过程、函数相关语句。

7.1使用步骤

准备工作:要有数据库、数据表

hr库,大家也可以自己建立一个数据库、数据表。

7.1.1 导入jar依赖

<!--导入相应的jar依赖-->
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.5.RELEASE</version>
    </dependency>
    <!--增加spring-jdbc的依赖-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.5.RELEASE</version>
    </dependency>
    <!--增加对mysql 连接的jar依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.19</version>
        </dependency>
    <!--增加对junit的jar依赖-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
    </dependency>
</dependencies>

7.1.2 配置数据源

数据源是什么???DataSource

//1.spring jdbc数据源;看下这个单词:DriverManager +DataSource
DriverManagerDataSource dataSource=new DriverManagerDataSource();
//手动设置驱动 url  用户名 密码;如果你的是5.1; com.mysql.jdbc.Driver
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/hr");
dataSource.setUsername("root");
dataSource.setPassword("root");

7.1.3 创建JdbcTemplate对象

//2.创建JdbcTemplate对象;
JdbcTemplate jdbcTemplate=new JdbcTemplate(); //new JdbcTemplate(dataSource)
jdbcTemplate.setDataSource(dataSource); //将上面的数据源对象,建立和JdbcTemplate对象的关联;

7.1.4 执行 增删改操作

//3.执行增删改查的操作;
jdbcTemplate.execute("delete  from account where id=1");

存在的问题是什么呢???

1.数据库配置的代码,放到了java里面,根据“高内聚,低耦合”原则,应该尽量做到分离;

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--通过spring配置文件来实现低耦合-->
    <!--1.配置DataSource数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/hr?useTimezone=true&amp;serverTimezone=CTT&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--这个对应setDataSource方法,将set后的方法名首字母小写-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

测试类:

 //1.要通过Spring来访问xml;new 完之后,Alt+Enter自动出来前面的变量名,然后名字可以自行修改
       ClassPathXmlApplicationContext  ac= new ClassPathXmlApplicationContext("beans.xml");
        //2.通过spring 配置文件来获取响应的对象
       JdbcTemplate jdbcTemplate= (JdbcTemplate) ac.getBean("jdbcTemplate");
jdbcTemplate.update("insert account(uid,money) values (10,99999)");
System.out.println("插入数据完毕");

针对Junit的知识点扩充:

额外的补充了一个知识点:

@Before:void方法之前

@After: void方法之后

@Test:用于单元测试的void方法

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Created by 张晨光 on 2020/6/29 15:52
 */
public class TestJdbcTemplateTwo {
    ClassPathXmlApplicationContext ac;
    JdbcTemplate jdbcTemplate;
    /**
     * 这个注解是在junit单元测试,常规的void方法之前进行;
     */
    @Before
    public void before(){
        System.out.println("开始了...");
        //1.要通过Spring来访问xml;new 完之后,Alt+Enter自动出来前面的变量名,然后名字可以自行修改
         ac= new ClassPathXmlApplicationContext("beans.xml");
        //2.通过spring 配置文件来获取响应的对象
        jdbcTemplate= (JdbcTemplate) ac.getBean("jdbcTemplate");
    }
    /**
     * 这个注解是在junit单元测试,常规的void方法之后进行;
     */
    @After
    public void after(){
        System.out.println("整体结束...");
    }
    @Test
    public void test(){        //3.执行操作--》增加操作;
        jdbcTemplate.update("insert account(uid,money) values (10,99999)");
        System.out.println("插入数据完毕");
    }
    @Test
    public void testUpdate(){
        //3.执行操作--》增加操作;
        jdbcTemplate.update("update account set money=9988 where uid=10");
        System.out.println("更新数据完毕");
    }
    @Test
    public void testDelete(){
        //3.执行操作--》增加操作;
        jdbcTemplate.update("delete  from account where uid=10");
        System.out.println("删除数据完毕");
    }
}

2.要扩充连接池技术,下次讲;

“低耦合"实现,使用Spring框架

总结:

1.已经学习过了Spring框架,对于复杂的企业业务逻辑,进行解耦操作,降低系统的复杂度;

2.Spring框架封装了原生 JDBC,就是JdbcTemplate,可以实现对数据库的增删改查操作,注意需要依赖于DataSource数据源类;

作业:

使用spring来对JdbcTemplate进行注入,实现增删改业务操作。

7.2 RowMapper

Spring提供的对数据库查询数据封装的接口。

通过实现接口,实现接口mapRow方法(),通过对数据的封装就是通过mapRow方法实现

@FunctionalInterface
public interface RowMapper<T> {
    @Nullable
    T mapRow(ResultSet var1, int var2) throws SQLException;
}

​ BeanPropertyRowMapper这是对RowMapper的实现类,它可以把ResultSet和实体类的字段进行实现自动映射,可以给同名字段进行封装。自动将一行数据映射到指定类的实例, 首先将这个类实例化,然后通过名称匹配的方式,映射到属性中去。

7.2.1 查询数据

       //需要提前去预习知识点:RowMapper
//        List<Account> accounts = jdbcTemplate.query("select * from account where money>?", new AccountRowMapper(), 2200);
        /*List<Account> accounts = jdbcTemplate.query("select * from account where money>?", new BeanPropertyRowMapper<Account>(Account.class), 2200);
        for(Account account:accounts){
            System.out.println(account);
        }*/
        //单一的账户
        /*List<Account> accounts = jdbcTemplate.query("select * from account where money=?", new BeanPropertyRowMapper<Account>(Account.class), 8899);
        System.out.println(accounts.get(0));*/
        //返回一行一列的数据;
        Integer count=jdbcTemplate.queryForObject("select Max(money) from account where money>?", Integer.class, 2200);
        System.out.println(count);

7.2.2 分层设计实现

作;
jdbcTemplate.update(“delete from account where uid=10”);
System.out.println(“删除数据完毕”);
}
}




2.要扩充连接池技术,下次讲;

“低耦合"实现,使用Spring框架

总结:

1.已经学习过了Spring框架,对于复杂的企业业务逻辑,进行解耦操作,降低系统的复杂度;

2.Spring框架封装了原生 JDBC,就是JdbcTemplate,可以实现对数据库的增删改查操作,注意需要依赖于DataSource数据源类;

作业:

使用spring来对JdbcTemplate进行注入,实现增删改业务操作。

## 7.2 RowMapper

> Spring提供的对数据库查询数据封装的接口。
>
> 通过实现接口,实现接口mapRow方法(),通过对数据的封装就是通过mapRow方法实现

@FunctionalInterface
public interface RowMapper {
@Nullable
T mapRow(ResultSet var1, int var2) throws SQLException;
}


​		BeanPropertyRowMapper这是对RowMapper的实现类,它可以把ResultSet和实体类的字段进行实现自动映射,可以给同名字段进行封装。自动将一行数据映射到指定类的实例, 首先将这个类实例化,然后通过名称匹配的方式,映射到属性中去。

### 7.2.1 查询数据

   //需要提前去预习知识点:RowMapper

// List accounts = jdbcTemplate.query(“select * from account where money>?”, new AccountRowMapper(), 2200);
/List accounts = jdbcTemplate.query(“select * from account where money>?”, new BeanPropertyRowMapper(Account.class), 2200);
for(Account account:accounts){
System.out.println(account);
}
/
//单一的账户
/List accounts = jdbcTemplate.query(“select * from account where money=?”, new BeanPropertyRowMapper(Account.class), 8899);
System.out.println(accounts.get(0));
/
//返回一行一列的数据;
Integer count=jdbcTemplate.queryForObject(“select Max(money) from account where money>?”, Integer.class, 2200);
System.out.println(count);


### 7.2.2 分层设计实现