1. 程式人生 > >spring_(21)Spring _使用 JdbcTemplate和JdbcDaoSupport

spring_(21)Spring _使用 JdbcTemplate和JdbcDaoSupport

JDBC Template簡介

  • 為了使JDBC更加易於使用,Spring在JDBC API上定義了一個抽象層,以此建立一個JDBC存取框架.

  • 作為SpringJDBC框架的核心,JDBC模板的設計目的是為不同型別的JDBC操作提供模板方法。每個模板都能控制整個過程,並允許覆蓋過程中的特定任務。通過這種方式,可以在儘可能保留靈活性的情況下,將資料庫存取的工作量降到最低。

    使用JDBCTemplate更新資料庫

    • 用sql語句和引數更新資料庫:

      update

      ​ public int update(String sql,Onject… args) throws DataAccessException

    • 批量更新資料庫:

      batchUpdate

      ​ public int[] batchUpdate(String sql,List<Object[]> batchArgs)

    • 查詢單行:

      queryForObject

      ​ public T queryForObject(String sql,ParameterizedRowMapper rm,Object… args) throws DataAccessException

    • 便利的BeanPropertyRowMapper 實現:

      ​ org.springframework.jdbc.core.simple

      Class ParameterizedBeanPropertyRowMapper

    • 查詢多行:

      query

      ​ public List query(String sql,ParameterizedRowMapper rm,Object… args) throws DataAccessException

    • 單值查詢:

      queryForObject

      ​ public T queryForObject(String sql,Class requiredType,Object… args) throws DataAccessException

      package com.
      spring.jdbc; 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 java.util.ArrayList; import java.util.List; public class JDBCTest { private ApplicationContext ctx = null; private JdbcTemplate jdbcTemplate; { ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate"); } /** * 獲取單個列的值,或做統計查詢 * 使用 queryForObject(String sql,Class<Long> requiredType); */ public void testQueryForObject2(){ String sql = "SELECT count(id) FORM employees"; long count = jdbcTemplate.queryForObject(sql,Long.class); System.out.println(count); } /** * 查到實體類的集合 * 注意呼叫的不是queryForList方法 */ public void testQueryForList(){ String sql = "SELECT id,last_name lastname,email from employees 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<Employees> requiredType, Object...args)方法! * 而需要呼叫 queryForObject(String sql,RowMapper<Emplyee> rowMapper, Object...args); * 1.其中的RowMapper 指定如何去對映結果集的行,常用的實現類為BeanPropertyMapper * 2.使用SQL中列的別名完成列名和類的屬性名的對映。例如last_name lastname * 3.不支援級聯屬性。JdbcTemplate 到底是一個JDBC的小工具,而不是ORM框架 */ public void testQueryForObject(){ String sql = "SELECT id,last_name lastname,email,dept_id \"department.id\" from employees where ID = ? "; RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class); Employee employee = jdbcTemplate.queryForObject(sql,rowMapper,1); System.out.println(employee); } /** * 執行批量更新:批量的INSERT, UPDATE, DELETE * 最後一個引數是Object[] 的List 型別:因為修改一條記錄需要一個Object的陣列,那麼多條不就需要多個Object的陣列嗎 */ public void testBatchUpdate(){ String sql = "INSERT INTO employees(last_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]",2}); batchArgs.add(new Object[]{"CC","[email protected]",3}); batchArgs.add(new Object[]{"DD","[email protected]",3}); batchArgs.add(new Object[]{"EE","[email protected]",2}); jdbcTemplate.batchUpdate(sql,batchArgs); } public void testUpdate(){ String sql = "UPDATE employees SET last_name = ? WHERE id = ?"; jdbcTemplate.update(sql,"Jack",2); }

簡化JDBC模板查詢

在這裡插入圖片描述

例子程式

基本結構

在這裡插入圖片描述

在這裡插入圖片描述

在這裡插入圖片描述

db.properties

jdbc.user=root
jdbc.password=****
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring4

jdbc.initPoolSize=5
jdbc.maxPoolSize=50

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

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

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

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

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


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


</beans>

Department.java

package com.spring.jdbc;

public class Department {

    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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.spring.jdbc;

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;

import javax.sql.DataSource;

/**
 * 不推薦使用JdbcDaoSupport,而直接使用JdbcTemplate作為Dao類的成員變數
 */
@Repository
public class DepartmentDao extends JdbcDaoSupport {

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

    public Department get(Integer id){
        String sql = "SELECT id, dept_name name FROM departments WHERE id = ?";
        RowMapper<Department> rowMapper = new BeanPropertyRowMapper<>(Department.class);
        return getJdbcTemplate().queryForObject(sql,rowMapper,id);
    }
}

Employee.java

package com.spring.jdbc;

public class Employee {

    private Integer id;
    private String lastname;
    private String email;

    private Department department;

    public Integer getId() {
        return id;
    }

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

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String last_name) {
        this.lastname = last_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 +
                ", lastname='" + lastname + '\'' +
                ", email='" + email + '\'' +
                ", department=" + department +
                '}';
    }
}

EmployeeDao.java

package com.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;

@Repository
public class EmployeeDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Employee get(Integer id){

        String sql = "SELECT id,last_name lastname,email,dept_id \"department.id\" from employees where ID = ? ";
        RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
        Employee employee = jdbcTemplate.queryForObject(sql,rowMapper,id);

        return employee;
    }

}

JDBCTest.java

package com.spring.jdbc;

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 java.util.ArrayList;
import java.util.List;

public class JDBCTest {

    private ApplicationContext ctx = null;
    private JdbcTemplate jdbcTemplate;
    private EmployeeDao employeeDao;
    private DepartmentDao departmentDao;

    {
        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
        employeeDao = ctx.getBean(EmployeeDao.class);
        departmentDao = ctx.getBean(DepartmentDao.class);
    }

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

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


    /**
     * 獲取單個列的值,或做統計查詢
     * 使用 queryForObject(String sql,Class<Long> requiredType);
     */
    public void testQueryForObject2(){
        String sql = "SELECT count(id) FORM employees";
        long count = jdbcTemplate.queryForObject(sql,Long.class);

        System.out.println(count);
    }


    /**
     * 查到實體類的集合
     * 注意呼叫的不是queryForList方法
     */
    public void testQueryForList(){
        String sql = "SELECT id,last_name lastname,email from employees 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<Employees> requiredType, Object...args)方法!
     * 而需要呼叫    queryForObject(String sql,RowMapper<Emplyee> rowMapper, Object...args);
     * 1.其中的RowMapper 指定如何去對映結果集的行,常用的實現類為BeanPropertyMapper
     * 2.使用SQL中列的別名完成列名和類的屬性名的對映。例如last_name lastname
     * 3.不支援級聯屬性。JdbcTemplate 到底是一個JDBC的小工具,而不是ORM框架
     */
    public void testQueryForObject(){
        String sql = "SELECT id,last_name lastname,email,dept_id \"department.id\" from employees where ID = ? ";
        RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<>(Employee.class);
        Employee employee = jdbcTemplate.queryForObject(sql,rowMapper,1);

        System.out.println(employee);

    }


    /**
     * 執行批量更新:批量的INSERT, UPDATE, DELETE
     * 最後一個引數是Object[] 的List 型別:因為修改一條記錄需要一個Object的陣列,那麼多條不就需要多個Object的陣列嗎
     */
    public void testBatchUpdate(){
        String sql = "INSERT INTO employees(last_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]",2});
        batchArgs.add(new Object[]{"CC","[email protected]",3});
        batchArgs.add(new Object[]{"DD","[email protected]",3});
        batchArgs.add(new Object[]{"EE","[email protected]",2});

        jdbcTemplate.batchUpdate(sql,batchArgs);

    }


   public void testUpdate(){
        String sql = "UPDATE employees SET last_name = ? WHERE id = ?";
        jdbcTemplate.update(sql,"Jack",2);
   }


}

Main.java

package com.spring.jdbc;

public class Main {

    public static void main(String[] args){
        JDBCTest a = new JDBCTest();
        a.testDepartmentDao();
    }
}

執行結果

在這裡插入圖片描述