• SpringJDBC模板类JdbcTemplate



    JdbcTemplate

    JdbcTemplate是Spring提供的一个JDBC模板类,是对JDBC的封装,简化JDBC代码。

    在实际工作中,一般Spring会集成其他的ORM框架,例如:MyBatis、Hibernate等。

    使用JdbcTemplate完成增删改查

    环境准备

    数据库表:t_user
    在这里插入图片描述

    IDEA中新建模块:spring6-jdbc

    引入相关依赖:
    pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <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/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.w</groupId>
        <artifactId>spring6-jdbc</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <repositories>
            <repository>
                <id>repository.spring.milestone</id>
                <name>Spring Milestone Repository</name>
                <url>https://repo.spring.io/milestone</url>
            </repository>
        </repositories>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>6.0.0-M2</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.2</version>
                <scope>test</scope>
            </dependency>
            <!--新增的依赖:mysql驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.30</version>
            </dependency>
            <!--新增的依赖:spring jdbc,这个依赖中有JdbcTemplate-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>6.0.0-M2</version>
            </dependency>
        </dependencies>
    
        <properties>
            <maven.compiler.source>17</maven.compiler.source>
            <maven.compiler.target>17</maven.compiler.target>
        </properties>
    
    </project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    准备实体类:表t_user对应的实体类User。
    User.java

    package com.w.spring6.bean;
    
    public class User {
        private Integer id;
        private String realName;
        private Integer age;
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", realName='" + realName + '\'' +
                    ", age=" + age +
                    '}';
        }
    
        public User() {
        }
    
        public User(Integer id, String realName, Integer age) {
            this.id = id;
            this.realName = realName;
            this.age = age;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getRealName() {
            return realName;
        }
    
        public void setRealName(String realName) {
            this.realName = realName;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    编写Spring配置文件:
    JdbcTemplate是Spring提供好的类,这类的完整类名是:org.springframework.jdbc.core.JdbcTemplate
    我们怎么使用这个类呢?new对象就可以了。怎么new对象,Spring最在行了。直接将这个类配置到Spring配置文件中,纳入Bean管理即可。
    spring.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    可以看到JdbcTemplate中有一个DataSource属性,这个属性是数据源,我们都知道连接数据库需要Connection对象,而生成Connection对象是数据源负责的。所以我们需要给JdbcTemplate设置数据源属性。

    所有的数据源都是要实现javax.sql.DataSource接口的。这个数据源可以自己写一个,也可以用写好的,我们这里自己先手写一个数据源。

    MyDataSource.java

    package com.w.spring6.jdbc;
    
    import javax.sql.DataSource;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.SQLFeatureNotSupportedException;
    import java.util.logging.Logger;
    
    public class MyDataSource implements DataSource {
        // 添加4个属性
        private String driver;
        private String url;
        private String username;
        private String password;
    
        // 提供4个setter方法
        public void setDriver(String driver) {
            this.driver = driver;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        // 重点写怎么获取Connection对象就行。其他方法不用管。
        @Override
        public Connection getConnection() throws SQLException {
            try {
                Class.forName(driver);
                Connection conn = DriverManager.getConnection(url, username, password);
                return conn;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        @Override
        public Connection getConnection(String username, String password) throws SQLException {
            return null;
        }
    
        @Override
        public PrintWriter getLogWriter() throws SQLException {
            return null;
        }
    
        @Override
        public void setLogWriter(PrintWriter out) throws SQLException {
    
        }
    
        @Override
        public void setLoginTimeout(int seconds) throws SQLException {
    
        }
    
        @Override
        public int getLoginTimeout() throws SQLException {
            return 0;
        }
    
        @Override
        public Logger getParentLogger() throws SQLFeatureNotSupportedException {
            return null;
        }
    
        @Override
        public <T> T unwrap(Class<T> iface) throws SQLException {
            return null;
        }
    
        @Override
        public boolean isWrapperFor(Class<?> iface) throws SQLException {
            return false;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88

    写完数据源,我们需要把这个数据源传递给JdbcTemplate。因为JdbcTemplate中有一个DataSource属性:
    spring.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
        
        <bean id="myDataSource" class="com.w.spring6.jdbc.MyDataSource">
            <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3307/idea-spring-test"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        bean>
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="myDataSource"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    新增

    编写测试程序:
    JdbcTest.java

    package com.w.spring6.test;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.jdbc.core.JdbcTemplate;
    
    public class JdbcTest {
    
        @Test
        public void testInsert(){
            // 获取JdbcTemplate对象
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
            JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
            // 执行插入操作
            // 注意:insert delete update的sql语句,都是执行update方法。
            String sql = "insert into t_user(id,real_name,age) values(?,?,?)";
            int count = jdbcTemplate.update(sql, null, "张三", 30);
            System.out.println("插入的记录条数:" + count);
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

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

    修改

    测试程序:

        @Test
        public void testUpdate(){
            // 获取JdbcTemplate对象
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
            JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
            // 执行更新操作
            String sql = "update t_user set real_name = ?, age = ? where id = ?";
            int count = jdbcTemplate.update(sql, "张三丰", 55, 1);
            System.out.println("更新的记录条数:" + count);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

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

    删除

    测试程序:

    @Test
    public void testDelete(){
        // 获取JdbcTemplate对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        // 执行delete
        String sql = "delete from t_user where id = ?";
        int count = jdbcTemplate.update(sql, 1);
        System.out.println("删除了几条记录:" + count);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

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

    查询一个对象

    测试程序:

    @Test
    public void testSelectOne(){
        // 获取JdbcTemplate对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        // 执行select
        String sql = "select id, real_name, age from t_user where id = ?";
        User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), 2);
        System.out.println(user);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

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

    注意:刚刚我们把数据库数据删完了,所以要提前插入一条数据

    不然就会出现:Incorrect result size: expected 1, actual 0
    原因:
    这个错误提示信息是我在使用JdbcTemplate查询数据库调用queryForObject()方法时,目的是把查询的结果封装成对象,但数据库里没有该条记录。导致报错提示,期望是1,但实际是0。

    还有一种情况是,查询到多条记录,由于queryForObject()方法只能一次封装一条记录,所以还会提示期望是1,实际是2或更多;

    解决方案:
    插入一条新数据。
    修改要查询的sql语句,确保查询到的结果只能为1条记录。

    批量添加

    测试程序:

    @Test
        public void testAddBatch(){
            // 获取JdbcTemplate对象
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
            JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
            // 批量添加
            String sql = "insert into t_user(id,real_name,age) values(?,?,?)";
    
            Object[] objs1 = {null, "小花", 2};
            Object[] objs2 = {null, "小明", 3};
            Object[] objs3 = {null, "小刚", 4};
            List<Object[]> list = new ArrayList<>();
            list.add(objs1);
            list.add(objs2);
            list.add(objs3);
    
            int[] count = jdbcTemplate.batchUpdate(sql, list);
            System.out.println(Arrays.toString(count));
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

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

    批量修改和批量删除

    和批量添加同理,只要修改sql语句就可以了,就不演示了,大家可以自己试一下。

    使用德鲁伊连接池(之前数据源是用我们自己写的)

    第一步:引入德鲁伊连接池的依赖。(毕竟是别人写的)
    德鲁伊依赖 pom.xml

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.8</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    第二步:将德鲁伊中的数据源配置到spring配置文件中。和配置我们自己写的一样。
    spring.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    
    
    
    
    
    
    
    
    
    
    
    
        <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3307/idea-spring-test"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        bean>
    
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="druidDataSource"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

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

  • 相关阅读:
    如何将本地文件上传到Gitee
    Mac中LaTex无法编译的问题
    Android平台轻量级RTSP服务模块编码前后数据源对接探究
    医学影像归档与通讯系统(PACS)系统源码 PACS三维图像后处理技术
    猿创征文|一名Python学者在CSDN的蜕变
    劳务派遣怎么交社保
    人家这才叫软件测试工程师,你那只是混口饭吃(附HR面试宝典)
    技术leader踩坑笔记:引入变化
    Real-Time Rendering——9.9.3 Smooth-Surface Subsurface Models光滑表面地下模型
    从RabbitMQ平滑迁移到RocketMQ技术实战
  • 原文地址:https://blog.csdn.net/m0_61689418/article/details/134442702