JDBC已经能够满足大部分用户最基本的需求,但是在使用JDBC必须自己管理数据库资源。如:获取PreparedStatement,设置SQL语句参数,关闭连接等。JdbcTemplate是Spring对JDBC的封装,目的是用JDBC更加易于使用。JdbcTemplate是Spring的一部分。JdbcTemplate处理资源的建立和释放。帮助避免一些常见的错误,如忘记关闭连接。JdbcTemplate运行核心的JDBC工作流,如Statement的建立和执行,使用时只需要提供SQL语句和提取结果。

       JdbcTemplate位于spring-jdbc.jar中,其全限定名为org.springframework.jdbc.core.JdbcTemplate。

JdbcTemplate主要提供以下几类方法:

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

一)添加依赖,POM.xml

    <dependencies>
        <!--測試包-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--sql server 驅動包-->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>7.2.2.jre8</version>
        </dependency>
        <!--Spring 框架容器包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <!--JdbcTemplate 包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
    </dependencies>

二)配置数据库属性配置文件 db.properties

jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost:1433;DatabaseName=testdb
jdbc.username=sa
jdbc.password=123.abc

三)配置Spring配置文件 applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--加載數據庫配置文件,讀取文件中數據-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

    <!--配置DriverManagerDataSource Bean,并注入屬性值-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    
    <!--配置JdbcTemplate Bean,并注入dataSource-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
    </bean>
</beans>

四)测试代码

1)使用update()方法,传入不同的sql语句及参数实现对应的新增、修改和删除等操作

新增数据

    @Test
    public void insert() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql="insert into account(name,money) values(?,?)";
        Object[] param={"may",5000f};
        int update = jdbcTemplate.update(sql, param);
        System.out.println("影響行數:"+update);
    }

修改数据

    @Test
    public void update(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql="update account set name=? , money=? where id=?";
        Object[] param={"August",8000f,13};
        int update = jdbcTemplate.update(sql, param);
        System.out.println("影響行數:"+update);
    }

删除数据

    @Test
    public void delete(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql="delete from account where id=?";
        int update = jdbcTemplate.update(sql, 13);
        System.out.println("影響行數:"+update);
    }

2,使用batchUpdate()方法实现批量新增、批量修改和批量删除等操作。与update()方法类似,传入sql语句和参数,只不过batchUpdate方法第二个参数是一个元素为Object[]数组类型的List集合。

批量新增数据

    @Test
    public void batchInsert(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql="insert into account(name,money) values(?,?)";
        List<Object[]> list=new ArrayList<>();
        list.add(new Object[]{"january",1000f});
        list.add(new Object[]{"february",2000f});
        list.add(new Object[]{"march",3000f});
        int[] batchUpdate = jdbcTemplate.batchUpdate(sql, list);
        System.out.println("影響行數"+batchUpdate.length);
    }

批量修改数据

    @Test
    public void batchUpdate(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql="update account set name=? , money=? where id=?";
        List<Object[]> list=new ArrayList<>();
        list.add(new Object[]{"april",4000f,17});
        list.add(new Object[]{"may",5000f,18});
        list.add(new Object[]{"june",6000f,19});
        int[] batchUpdate = jdbcTemplate.batchUpdate(sql, list);
        System.out.println("影響行數:"+batchUpdate.length);
    }

批量删除数据

    @Test
    public void batchDelete(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql="delete from account where id=?";
        List<Object[]> list=new ArrayList<>();
        list.add(new Object[]{10});
        list.add(new Object[]{11});
        list.add(new Object[]{12});
        int[] batchUpdate = jdbcTemplate.batchUpdate(sql, list);
        System.out.println("影響行數:"+batchUpdate.length);
    }

3,使用query()方法

POJO目录下Account.java

public class Account {
    private int id;
    private String name;
    private float money;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getMoney() {
        return money;
    }

    public void setMoney(float money) {
        this.money = money;
    }
}

queryForObject()方法读取单个对象

    @Test
    public void queryAccountById(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql="select * from account where id=?";
        Account account = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Account.class), 15);
        System.out.println(account);
    }

query()方法读取多个对象

    @Test
    public void queryAccountList() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql = "select * from account";
        List<Account> accountList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Account.class));
        for (int i = 0; i < accountList.size(); i++) {
            Account account = accountList.get(i);
            System.out.println(account);
        }
    }

获取某个记录某列或者count、avg、sum等函数返回唯一值

    @Test
    public void getCount(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql="select count(*) from account";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        System.out.println(count);
    }

 

QueryRunner与JdbcTemplate的异同:

两者都是通过update()实现新增、修改、删除等操作。而就query()方法而言,queryRunner.query(sql,new BeanHandler<>(mappedClass),parameters)实现读取单个对象,queryRunner.query(sql,new BeanListHandler<>(mappedClass),parameters)实现读取多个对象;jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(mappedClass),parameters)实现读取单个对象,jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(mappedClass),parameters)实现读取多个对象。

将查询结果返回的ResultSet对象映射目标对象上,QueryRunner映射的接口是ResultSetHandler,而JdbcTemplate映射的接口是RowMapper。

 

 posted on 2019-10-27 15:31  会飞的金鱼  阅读(330)  评论(0)    收藏  举报