Spring-jdbcTemplate-配置数据库连接池,配置文件方式beans.xml

1、jdbc.properties

java 复制代码
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///studb
jdbc.user=root
jdbc.pwd=123456

2、beans.xml

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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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 http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--导入jdbc.properties-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--创建数据源连接处-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.pwd}"/>
        <property name="initialSize" value="5"/>
        <property name="maxWait" value="5000"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

3、Student.java

java 复制代码
package com.atguigu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private Integer id;
    private String name;
    private String gender;
    private Integer age;
    private String classBean;
}

4、JdbcTemplateTest.java

java 复制代码
package com.atguigu;
import com.atguigu.pojo.Student;
import org.junit.jupiter.api.Test;
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.test.context.junit.jupiter.SpringJUnitConfig;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@SpringJUnitConfig(locations = "classpath:beans.xml")
public class JdbcTemplateTest {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //测试连接数据库
    @Test
    public void TestConnection() throws SQLException {
        System.out.println(dataSource.getConnection()==null?"连接失败":"连接成功");//连接成功
    }

    //测试插入操作
    @Test
    public void InsertTest() {
        Student s1= new Student(0, "阿碧", "女", 18, "Java1班");
        String sql = "insert into students values(0,?,?,?,?)";
        jdbcTemplate.update(sql, s1.getName(), s1.getGender(), s1.getAge(), s1.getClassBean());
    }

    //演示删除学生信息测试方法
    @Test
    public void DeleteTest() {
        String sql = "delete from students where id=?";
        jdbcTemplate.update(sql, 0);
    }

    //演示查询单个字段值
    @Test
    public void QueryTest() {
        String sql = "select name from students where id=?";
        String name = jdbcTemplate.queryForObject(sql, String.class, 8);
        System.out.println("name = " + name);//name = 吴十
    }

    //演示查询单个实体对象
    @Test
    public void QueryObjectTest() {
        String sql = "select * from students where id=?";
        Student s = jdbcTemplate.queryForObject(sql, new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
                return new Student(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getString(5));
            }
        }, 8);
        System.out.println("s = " + s);//s = Student(id=8, name=吴十, gender=男, age=19, classBean=高中二班)
    }
    //演示查询单个实体对象
    @Test
    public void QueryObjectLambdaTest() {
        String sql = "select * from students where id=?";
        Student s = jdbcTemplate.queryForObject(sql,(rs,rowNum)->
            new Student(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getString(5))
                , 8);
        System.out.println("s = " + s);//s = Student(id=8, name=吴十, gender=男, age=19, classBean=高中二班)
    }


    //演示查询实体对象列表
    @Test
    public void QueryObjectListTest() {
        String sql = "select id,name,gender,age,class as classBean from students";
        List<Student> studentList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
        studentList.forEach(System.out::println);
        //Student(id=1, name=张三, gender=男, age=20, classBean=高中一班)
        //Student(id=2, name=李四, gender=男, age=19, classBean=高中二班)
        //Student(id=3, name=王五, gender=女, age=18, classBean=高中一班)
        //Student(id=4, name=赵六, gender=女, age=20, classBean=高中三班)
        //Student(id=5, name=刘七, gender=男, age=19, classBean=高中二班)
        //Student(id=6, name=陈八, gender=女, age=18, classBean=高中一班)
        //Student(id=7, name=杨九, gender=男, age=20, classBean=高中三班)
        //Student(id=8, name=吴十, gender=男, age=19, classBean=高中二班)
    }
}

5、studb.sql

sql 复制代码
create database studb;

use studb;

CREATE TABLE students (
  id INT PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  gender VARCHAR(10) NOT NULL,
  age INT,
  class VARCHAR(50)
);

INSERT INTO students (id, name, gender, age, class)
VALUES
  (1, '张三', '男', 20, '高中一班'),
  (2, '李四', '男', 19, '高中二班'),
  (3, '王五', '女', 18, '高中一班'),
  (4, '赵六', '女', 20, '高中三班'),
  (5, '刘七', '男', 19, '高中二班'),
  (6, '陈八', '女', 18, '高中一班'),
  (7, '杨九', '男', 20, '高中三班'),
  (8, '吴十', '男', 19, '高中二班');

6、父工程pom.xml

XML 复制代码
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>6.0.6</spring.version>
        <junit.version>5.3.1</junit.version>
        <lombok.version>1.18.20</lombok.version>
        <mysql.version>8.0.25</mysql.version>
        <druid.version>1.2.8</druid.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
            </dependency>

            <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-api</artifactId>
                <version>${junit.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
                <scope>test</scope>
            </dependency>

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>

            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>

        </dependencies>
    </dependencyManagement>

7、子工程pom.xml

XML 复制代码
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>


spring-jdbc-template是Spring框架中提供的一个JDBC模板,简化了开发者对JDBC API的调用。你可以使用它来执行各种JDBC操作,如查询、插入、更新、删除等。下面是使用spring-jdbc-template的步骤:

  1. 添加spring-jdbc依赖

首先需要在Maven或Gradle项目中添加spring-jdbc依赖。

XML 复制代码
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.6</version>
</dependency>
 
  1. 配置数据源

配置使用的数据源,在Spring配置文件中添加以下配置。

XML 复制代码
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/test"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
</bean>
  1. 配置JdbcTemplate

配置JdbcTemplate,配置JdbcTemplate时需要注入数据源。

XML 复制代码
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
</bean>
  1. 使用JdbcTemplate

最后,你可以在Java代码中使用JdbcTemplate。

java 复制代码
@Autowired
private JdbcTemplate jdbcTemplate;

public void insert(User user) {
    String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
    jdbcTemplate.update(sql, user.getName(), user.getAge());
}

以上是使用spring-jdbc-template的步骤,你可以根据项目的需要来调整代码实现,具体的JDBC操作方法可以在Spring的官方文档中查找。

相关推荐
冰帝海岸3 小时前
01-spring security认证笔记
java·笔记·spring
没书读了4 小时前
ssm框架-spring-spring声明式事务
java·数据库·spring
代码小鑫7 小时前
A043-基于Spring Boot的秒杀系统设计与实现
java·开发语言·数据库·spring boot·后端·spring·毕业设计
真心喜欢你吖7 小时前
SpringBoot与MongoDB深度整合及应用案例
java·spring boot·后端·mongodb·spring
斗-匕9 小时前
Spring事务管理
数据库·spring·oracle
Doker 多克12 小时前
Spring AI 框架使用的核心概念
人工智能·spring·chatgpt
请叫我青哥15 小时前
第五十二条:谨慎使用重载
java·spring
孟秋与你17 小时前
【spring】spring单例模式与锁对象作用域的分析
java·spring·单例模式
luckywuxn17 小时前
Spring Cloud Alibaba、Spring Cloud 与 Spring Boot各版本的对应关系
spring boot·spring·spring cloud
是程序喵呀18 小时前
SpringMVC详解
java·spring·spring-mvc