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

运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42036647/article/details/84785653
今日推荐