1. 程式人生 > >Spring 學習(二十一)——使用 JdbcTemplate

Spring 學習(二十一)——使用 JdbcTemplate

JdbcTemplate 簡介

  • 為了使 JDBC 更加易於使用, Spring JDBC API 上定義了一個抽象層, 以此建立一個 JDBC 存取框架.
  • 作為 Spring JDBC 框架的核心, JDBC 模板的設計目的是為不同型別的 JDBC 操作提供模板方法. 每個模板方法都能控制整個過程, 並允許覆蓋過程中的特定任務. 通過這種方式, 可以在儘可能保留靈活性的情況下, 將資料庫存取的工作量降到最低.

使用 JdbcTemplate 更新資料庫

  • sql 語句和引數更新資料庫
public void testUpdate() {
    String sql = "update employee set name = ? where id = ?";
    int row = jdbcTemplate.update(sql, "Rose", 4);
    System.out.println(row);
}
  • 批量更新資料庫
public void testBatchUpdate() {
    String sql = "insert into employee (name, email, dept_id) values (?, ?, ?)";

    List<Object[]> batchArgs = new ArrayList<>();
    batchArgs.add(new Object[]{"AA", "[email protected]", 1});
    batchArgs.add(new Object[]{"BB", "[email protected]
", 3}); batchArgs.add(new Object[]{"CC", "[email protected]", 4}); batchArgs.add(new Object[]{"DD", "[email protected]", 3}); batchArgs.add(new Object[]{"EE", "[email protected]", 2}); int[] result = jdbcTemplate.batchUpdate(sql, batchArgs); System.out.println(Arrays.toString(result)); }

使用 JdbcTemplate 查詢資料庫

  • 查詢單行
public void testQueryForObject() {
    String sql = "SELECT id, name, email, dept_id FROM employee WHERE id = ?";

    RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
    Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, 1);
    System.out.println(employee);
}
  • 便利的 BeanPropertyRowMapper 實現

  • 查詢多行
public void testQueryForList() {
    String sql = "SELECT id, name, email FROM employee WHERE id > ?";

    RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
    List<Employee> employees = jdbcTemplate.query(sql, rowMapper, 5);
    System.out.println(employees);
}
  • 單值查詢:
public void testQueryForObject() {
    String sql = "SELECT count(id) FROM employee WHERE id > ?";

    long count = jdbcTemplate.queryForObject(sql, Long.class, 5);
    System.out.println(count);
}

簡化 JDBC 模板查詢

  • 每次使用都建立一個 JdbcTemplate 的新例項, 這種做法效率很低下.
  • JdbcTemplate 類被設計成為執行緒安全的, 所以可以再 IOC 容器中宣告它的單個例項, 並將這個例項注入到所有的 DAO 例項中.
  • JdbcTemplate 也利用了 Java 1.5 的特定(自動裝箱, 泛型, 可變長度等)來簡化開發
  • Spring JDBC 框架還提供了一個 JdbcDaoSupport 類來簡化 DAO 實現. 該類聲明瞭 jdbcTemplate 屬性, 它可以從 IOC 容器中注入, 或者自動從資料來源中建立.

注入 JDBC 模板示例程式碼

擴充套件 JdbcDaoSupport 示例程式碼

程式碼示例:

1、資料庫表的建立如下:

employee表

department表

2、目錄結構

Spring
|——src
|——|——com.hzyc.spring.jdbc
|——|——|——department.java
|——|——|——departmentDao.java
|——|——|——employee.java
|——|——|——employeeDao.java
|——|——|——JdbcTest.java
|——|——application-context.xml
|——|——db.properties

2、db.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring
jdbc.user=root
jdbc.password=root
 
jdbc.initPoolSize=5
jdbc.maxPoolSize=10

3、application-context.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
	   http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="com.hzyc.spring"/>

    <!--匯入資原始檔-->
    <context:property-placeholder location="classpath:db.properties"/>

    <!--配置 c3p0 資料來源-->
    <bean id="dataSource"
          class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>

        <property name="initialPoolSize" value="${jdbc.initPoolSize}"/>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
    </bean>

    <!--配置 Spring 的 Jdbc Template-->
    <bean id="jdbcTemplate"
          class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

 department.java

package com.hzyc.spring.jdbc;

/**
 * @author xuehj2016
 * @Title: Department
 * @ProjectName Spring
 * @Description: TODO
 * @date 2018/12/21 14:43
 */
public class Department {
    private int id;
    private String name;

    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;
    }

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

departmentDao.java

package com.hzyc.spring.jdbc;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

/**
 * @author xuehj2016
 * @Title: DepartmentDao
 * @ProjectName Spring
 * @Description: 不推薦使用 JdbcDaoSupport, 而推薦直接使用 JdbcTemplate 作為 Dao 類的成員變數
 * @date 2018/12/21 18:34
 */
@Repository
public class DepartmentDao extends JdbcDaoSupport {

    @Autowired
    public void setDataSource2(DataSource dataSource) {
        setDataSource(dataSource);
    }

    public Department get(int id) {
        String sql = "SELECT id, name FROM department WHERE id = ?";
        RowMapper<Department> rowMapper = new BeanPropertyRowMapper<>(Department.class);

        return getJdbcTemplate().queryForObject(sql, rowMapper, id);
    }
}

employee.java

package com.hzyc.spring.jdbc;

/**
 * @author xuehj2016
 * @Title: Employee
 * @ProjectName Spring
 * @Description: TODO
 * @date 2018/12/21 14:41
 */
public class Employee {
    private int id;
    private String name;
    private String email;
    private Department department;

    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 String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", department=" + department +
                '}';
    }
}

employeeDao.java

package com.hzyc.spring.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

/**
 * @author xuehj2016
 * @Title: EmployeeDao
 * @ProjectName Spring
 * @Description: TODO
 * @date 2018/12/21 18:35
 */
@Repository
public class EmployeeDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Employee get(int id) {
        String sql = "SELECT id, name, email FROM employee WHERE id = ?";
        RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
        Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, id);

        return employee;
    }
}

JdbcTest.java

package com.hzyc.spring.jdbc;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author xuehj2016
 * @Title: JdbcTest
 * @ProjectName Spring
 * @Description: TODO
 * @date 2018/12/21 14:02
 */
public class JdbcTest {

    private ApplicationContext applicationContext;
    private JdbcTemplate jdbcTemplate;
    private EmployeeDao employeeDao;
    private DepartmentDao departmentDao;

    {
        applicationContext = new ClassPathXmlApplicationContext("application-context.xml");
        jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
        employeeDao = (EmployeeDao) applicationContext.getBean("employeeDao");
        departmentDao = (DepartmentDao) applicationContext.getBean("departmentDao");
    }

    @Test
    public void testDataSource() throws SQLException {
        DataSource dataSource = (DataSource) applicationContext.getBean("dataSource");
        System.out.println(dataSource.getConnection());
    }

    /**
     * 執行 insert ,update , delete
     */
    @Test
    public void testUpdate() {
        String sql = "update employee set name = ? where id = ?";
        int row = jdbcTemplate.update(sql, "Rose", 4);
        System.out.println(row);
    }

    /**
     * 執行批量更新 : 批量的 insert ,update ,delete
     * 最後一個引數是 Object[] 的 List 型別;因為修改一條記錄需要一個 Object 的陣列,多條就需要多個 Object 的陣列
     */
    @Test
    public void testBatchUpdate() {
        String sql = "insert into employee (name, email, dept_id) values (?, ?, ?)";

        List<Object[]> batchArgs = new ArrayList<>();
        batchArgs.add(new Object[]{"AA", "[email protected]", 1});
        batchArgs.add(new Object[]{"BB", "[email protected]", 3});
        batchArgs.add(new Object[]{"CC", "[email protected]", 4});
        batchArgs.add(new Object[]{"DD", "[email protected]", 3});
        batchArgs.add(new Object[]{"EE", "[email protected]", 2});

        int[] result = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(result));
    }

    /**
     * 從資料庫中獲取一條記錄, 實際得到對應的一個物件
     * 注意不是呼叫 queryForObject(String sql, Class<Employee> requiredType, Object... args) 方法!
     * 而需要呼叫 queryForObject(String sql, RowMapper<Employee> rowMapper, Object... args)
     * 1. 其中的 RowMapper 指定如何去對映結果集的行, 常用的實現類為 BeanPropertyRowMapper
     * 2. 使用 SQL 中列的別名完成列名和類的屬性名的對映. 例如 dept_id as department.id
     * 3. 不支援級聯屬性. JdbcTemplate 到底是一個 JDBC 的小工具, 而不是 ORM 框架
     */
    @Test
    public void testQueryForObject() {
        String sql = "SELECT id, name, email, dept_id FROM employee WHERE id = ?";

        RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
        Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, 1);
        System.out.println(employee);
    }

    /**
     * 查到實體類的集合
     * 注意呼叫的不是 queryForList 方法,而是 query 方法
     */
    @Test
    public void testQueryForList() {
        String sql = "SELECT id, name, email FROM employee WHERE id > ?";

        RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
        List<Employee> employees = jdbcTemplate.query(sql, rowMapper, 5);
        System.out.println(employees);
    }

    /**
     * 獲取單個列的值, 或做統計查詢
     * 使用 queryForObject(String sql, Class<Long> requiredType)
     */
    @Test
    public void testQueryForObject2() {
        String sql = "SELECT count(id) FROM employee WHERE id > ?";

        long count = jdbcTemplate.queryForObject(sql, Long.class, 5);
        System.out.println(count);
    }

    @Test
    public void testEmployeeDao() {
        System.out.println(employeeDao.get(1));
    }

    @Test
    public void testDepartmentDao() {
        System.out.println(departmentDao.get(1));
    }
}