Spring:JDBCTemplate

JDBCTemplate

在这里插入图片描述

概述

JDBC(Java DataBase Connectivity,Java 数据库连接), 一 种用于执行 SQL 语句的 Java API(Application Programming Interface , 应用程序设计接口 ),可以为多种关系数据库提供统一访问,由一组用 Java 语言编写的类和接口组成。

JDBCTemplate ,是一个 JDBC 的模板,Spring 封装了 JDBC 常用的操作,简化了 JDBC API 的使用和开发人员的工作,提供了便捷、安全和高效的访问数据库的方式。

简单示例:
首先在 pom.xml 文件中添加以下配置:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.25</version>
</dependency>

然后创建一个带有 id 和 name 属性的 JDBC 表:
在这里插入图片描述

再根据 JDBC 表定义一个与之相映射的 JDBC 类:

package cn.edu.springdemo.jdbc;

public class JDBC {
    
    
    public int id;
    public String name;

    public JDBC() {
    
    
        super();
    }

    public JDBC(int id, String name) {
    
    
        this.id = id;
        this.name = name;
    }

    public int getId() {
    
    
        return id;
    }

    public String getName() {
    
    
        return name;
    }

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

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

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

接着,定义一个接口 JDBCDao ,声明一系列常用访问数据库的方法:

package cn.edu.springdemo.jdbc;

import java.util.List;

public interface JDBCDao {
    
    
    public void add(JDBC jdbc);
    public void delete(int id);
    public void update(JDBC jdbc);
    public JDBC select(int id);
    public List<JDBC> selectAll();
}

再创建该接口的实现类 JDBCDaoImpl :

package cn.edu.springdemo.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.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("JDBCDao")
public class JDBCDaoImpl implements JDBCDao {
    
    
    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //增添
    public void add(JDBC jdbc){
    
    
        String sql = "INSERT INTO `jdbc` (`name`) VALUES (:name);";
        SqlParameterSource sqlParameterSource = new BeanPropertySqlParameterSource(jdbc);
        namedParameterJdbcTemplate.update(sql,sqlParameterSource);
    }
    /**
     *     增添或者使用如下方法
     *     public void add(JDBC jdbc){
     *         String sql = "INSERT INTO `jdbc` (`name`) VALUES (?);";
     *         Object[] args = {jdbc.getName()};
     *         jdbcTemplate.update(sql,args);
     *     }
     */

    //删除
    public void delete(int id){
    
    
        String sql = "DELETE FROM `jdbc` WHERE `id`=?;";
        jdbcTemplate.update(sql,id);
    }

    //修改
    public void update(JDBC jdbc){
    
    
        String sql = "UPDATE `jdbc` SET `name`=? WHERE `id`=?;";
        Object[] args = {
    
    jdbc.getName(),jdbc.getId()};
        jdbcTemplate.update(sql,args);
    }

    //id查询
    public JDBC select(int id){
    
    
        String sql = "SELECT `id`,`name` FROM `jdbc` WHERE `id`=?;";
        RowMapper<JDBC> list = new BeanPropertyRowMapper<>(JDBC.class);
        return jdbcTemplate.queryForObject(sql,list,id);
    }

    //查询
    public List<JDBC> selectAll(){
    
    
        String sql = "SELECT `id`,`name` FROM `jdbc`;";
        RowMapper<JDBC> rowMapper = new BeanPropertyRowMapper<>(JDBC.class);
        List<JDBC> list = jdbcTemplate.query(sql,rowMapper);
        return list;
    }
}

另外在 resources 目录下创建 jdbc.properties ,添加以下内容:

jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student?useSSL=false&serverTimezone=UTC
jdbc.user=root
jdbc.password=0123
acquireIncrement=5
initialPoolSize=10
minPoolSize=5
maxPoolSize=100
maxStatements=2
maxStatementsPerConnection=5

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:component-scan base-package="cn.edu.springdemo.jdbc" />

    <!-- 在 Bean 的外部属性文件的使用中有所提及 -->
    <!-- 使用context命名空间,通过 location 属性指定 properties 文件位置 -->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 连接MySQL数据库的基本信息的配置 -->
        <!-- 驱动程序类名:com.mysql.jdbc.Driver -->
        <property name="driverClass" value="${jdbc.driverClass}" />
        <!-- JDBC URL:jdbc:mysql://<host>:<port>/<database_name> -->
        <property name="jdbcUrl" value="${jdbc.url}" />
        <!-- 数据库用户名 -->
        <property name="user" value="${jdbc.user}" />
        <!-- 数据库用户密码 -->
        <property name="password" value="${jdbc.password}" />
        <!-- 若数据库中的连接数量不足时,向数据库申请的连接数量 -->
        <property name="acquireIncrement" value="${acquireIncrement}" />
        <!-- 初始化数据库连接池时连接的数量 -->
        <property name="initialPoolSize" value="${initialPoolSize}" />
        <!-- 数据库连接池最小的数据库连接数 -->
        <property name="minPoolSize" value="${minPoolSize}" />
        <!-- 数据库连接池最大的数据库连接数 -->
        <property name="maxPoolSize" value="${maxPoolSize}" />
        <!-- C3P0数据库连接池可以维护的Statement数量 -->
        <property name="maxStatements" value="${maxStatements}" />
        <!-- 每个连接同时可以使用Statement的数量 -->
        <property name="maxStatementsPerConnection" value="${maxStatementsPerConnection}" />
    </bean>

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

    <!-- 配置namedParameterJdbcTemplate,注入dataSource -->
    <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg type="javax.sql.DataSource" ref="dataSource"/>
    </bean>
</beans>

最后测试结果:

package cn.edu.springdemo.jdbc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class JDBCTest {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("jdbc.xml");
        JDBCDao jdbcDao = (JDBCDao) applicationContext.getBean("JDBCDao");
        System.out.println("第一次查询:" + jdbcDao.selectAll());

        JDBC jdbc = new JDBC();
        jdbc.setName("赵子龙");
        jdbcDao.add(jdbc); //新增

        jdbc.setId(10106);
        jdbc.setName("赵云");
        jdbcDao.update(jdbc); //修改

        System.out.println("第二次查询:" + jdbcDao.selectAll());
        System.out.println("id查询:" + jdbcDao.select(10101));

        jdbcDao.delete(10104); //删除
    }
}

结果如图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_56886142/article/details/130876224