Spring JdbcTemplate详解

JdbcTemplate简介

  Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中。

JdbcTemplate是线程安全的。

  JdbcTemplate位于中。其全限定命名为org.springframework.jdbc.core.JdbcTemplate。要使用JdbcTemlate还需一个这个包包含了一下事务和异常控制

  

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

  • execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;

  • update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;

  • query方法及queryForXXX方法:用于执行查询相关语句;

  • call方法:用于执行存储过程、函数相关语句。

具体使用:

在src下面新建一个属性配置文件

user=root
password=
jdbcUrl=jdbc:mysql://localhost:3306/springtransaction
dirverClass=com.mysql.jdbc.Driver
initPoolSize=5
maxPoolSize=10

Spring配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/jdbc
    http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
    http://www.springframework.org/schema/cache
    http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util.xsd">
    
    
    <!-- 导入db.properties源文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 配置c3p0数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${user}"></property>
        <property name="password" value="${password}"></property>
        <property name="jdbcUrl" value="${jdbcUrl}"></property>
        <property name="driverClass" value="${dirverClass}"></property>
        <property name="initialPoolSize" value="${initPoolSize}"></property>
        <property name="maxPoolSize" value="${maxPoolSize}"></property>
    </bean>
    <!-- 配置spring的JdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

相关依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.yangjing.springTransaction</groupId>
  <artifactId>springTransaction</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springTransaction Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- c3p0依赖 -->
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    <!-- mysql数据库驱动依赖 -->
    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.24</version>
     </dependency>
    <!--spring上下文包,在加载spring配置文件时用到-->  
      <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-context</artifactId>  
            <version>4.2.4.RELEASE</version>  
    </dependency>
    <!--spring的jdbc-->  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-jdbc</artifactId>  
        <version>4.2.4.RELEASE</version>  
    </dependency>   
  </dependencies>
  <build>
    <finalName>springTransaction</finalName>
  </build>
</project>

测试

package com.spring.jdbc;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
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;

public class JDBCTest {
    private ApplicationContext applicationContext = null;
    private JdbcTemplate jdbcTemplate;
    {
        applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
    }
    
    @Test
    public void testDataSource() throws SQLException{
        DataSource dataSource = applicationContext.getBean(DataSource.class);
        System.out.println(dataSource.getConnection());
        
    }
    
    //执行 insert update delete操作
    @Test
    public void testUpdate(){
        String sql = "update student set name = ? where id = ?";
        jdbcTemplate.update(sql, "sunwukong",4);
    }
    
    //测试批量更新:insert update delete操作都可以
    @Test
    public void testBatchUpdate(){
        String sql = "insert into student(name,class_id) values(?,?)";
        List<Object[]> batchArgs = new ArrayList<Object[]>();
        batchArgs.add(new Object[]{"AA",1});
        batchArgs.add(new Object[]{"BB",2});
        jdbcTemplate.batchUpdate(sql, batchArgs);
    }
    //测试查询一个(实体对象)
    @Test
    public void testQueryOne(){
        String sql = "select id,name,class_id from student where id = ?";
        RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>(Student.class);
        Student student = jdbcTemplate.queryForObject(sql, rowMapper, 1);
        System.out.println(student);
    }
        
    //测试查询一组对象(对象集合)
    @Test
    public void testQueryList(){
        String sql = "select id,name,class_id from student where class_id = ?";
        RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>(Student.class);
        List<Student> list = jdbcTemplate.query(sql, rowMapper, 1);
        System.out.println(list);
        
    }
    
    //测试统计查询
    @Test
    public void testCount(){
        String sql = "select count(id) from student where id > ?";
        long count = jdbcTemplate.queryForObject(sql, Long.class,3);
        System.out.println(count);
    }
    
}


实体类

package com.spring.jdbc;

public class Student {
    private Integer id;
    private String name;
    private Classes classes;
    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;
    }
    
    public Classes getClasses() {
        return classes;
    }
    public void setClasses(Classes classes) {
        this.classes = classes;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", classes=" + classes + "]";
    }
    
    
}

package com.spring.jdbc;

public class Classes {
    private Integer id;
    private String name;
    private Integer classId;
    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;
    }
    public Integer getClassId() {
        return classId;
    }
    public void setClassId(Integer classId) {
        this.classId = classId;
    }
    @Override
    public String toString() {
        return "Classes [id=" + id + ", name=" + name + ", classId=" + classId + "]";
    }
    
}

原文地址:https://www.cnblogs.com/DanielJing/p/6405794.html