Spring系列文章:Spring使用JdbcTemplate

news2025/3/1 4:44:17

一、简介

JdbcTemplate是Spring提供的⼀个JDBC模板类,是对JDBC的封装,简化JDBC代码。 当然,你也可以不⽤,可以让Spring集成其它的ORM框架,例如:MyBatis、Hibernate等。

第一步:引入依赖

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <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.2</version>
        </dependency>

二、整合JdbcTemplate

第二步:编写Spring配置⽂件

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

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"></bean>

 

可以看到JdbcTemplate中有⼀个DataSource属性,这个属性是数据源,我们都知道连接数据库需要 Connection对象,⽽⽣成Connection对象是数据源负责的。

所以我们需要给JdbcTemplate设置数据源 属性。 所有的数据源都是要实现javax.sql.DataSource接⼝的。这个数据源可以⾃⼰写⼀个,也可以⽤写好的, ⽐如:阿⾥巴巴的德鲁伊连接池,c3p0,dbcp等。我们这⾥⾃⼰先⼿写⼀个数据源。

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

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

<?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">
    <bean id="myDataSource" class="com.springcode.example.entity.MyDataSource">
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring6"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="myDataSource"/>
    </bean>
</beans>

三、增删改查

1、增加


public class SpringTest {
    @Test
    public void test(){
        // 获取JdbcTemplate对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
                /*注意:insert delete update的sql语句,都是执⾏update⽅法。update⽅法有两个参数:
                第⼀个参数:要执⾏的SQL语句。(SQL语句中可能会有占位符 ? )
                第⼆个参数:可变⻓参数,参数的个数可以是0个,也可以是多个。⼀般是SQL语句中有⼏个问号,
                则对应⼏个参数。*/
                String sql = "insert into t_user(id,real_name,age) values(?,?,?)";
        int count = jdbcTemplate.update(sql, null, "张三", 30);
        System.out.println("插⼊的记录条数:" + count);
    }
}

2、修改

public class SpringTest {
    @Test
    public void test(){
        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);
    }
}

3、删除

public class SpringTest {
    @Test
    public void test(){
        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);
    }
}

4、查询一个对象

public class SpringTest {
    @Test
    public void test(){
        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 = ?";
        /*
        queryForObject⽅法三个参数:
        第⼀个参数:sql语句
        第⼆个参数:Bean属性值和数据库记录⾏的映射对象。在构造⽅法中指定映射的对象类型。
        第三个参数:可变⻓参数,给sql语句的占位符问号传值。
         */
        User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), 2);
        System.out.println(user);
    }
}

5、查询多个对象

public class SpringTest {
    @Test
    public void test(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        // 执⾏select
        String sql = "select id, real_name, age from t_user";
        List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
        System.out.println(users);
    }
}

6、查询⼀个值

public class SpringTest {
    @Test
    public void test(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        // 执⾏select
        String sql = "select count(1) from t_user";
        Integer count = jdbcTemplate.queryForObject(sql, int.class); // 这⾥⽤Integer.class也可以
        System.out.println("总记录条数:" + count);
    }
}

7、批量添加

public class SpringTest {
    @Test
    public void test(){
        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, "⼩花", 20};
        Object[] objs2 = {null, "⼩明", 21};
        Object[] objs3 = {null, "⼩刚", 22};
        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));
    }
}

8、批量修改

public class SpringTest {
    @Test
    public void test(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        // 批量修改
        String sql = "update t_user set real_name = ?, age = ? where id = ?";
        Object[] objs1 = {"⼩花11", 10, 2};
        Object[] objs2 = {"⼩明22", 12, 3};
        Object[] objs3 = {"⼩刚33", 9, 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));
    }
}

9、批量删除

public class SpringTest {
    @Test
    public void test(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        // 批量删除
        String sql = "delete from t_user where id = ?";
        Object[] objs1 = {2};
        Object[] objs2 = {3};
        Object[] objs3 = {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));
    }
}

10、使⽤回调函数

public class SpringTest {
    @Test
    public void test(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
        String sql = "select id, real_name, age from t_user where id = ?";
        User user = jdbcTemplate.execute(sql, new PreparedStatementCallback<User>() {
            @Override
            public User doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                User user = null;
                ps.setInt(1, 5);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    user = new User();
                    user.setId(rs.getInt("id"));
                    user.setRealName(rs.getString("real_name"));
                    user.setAge(rs.getInt("age"));
                }
                return user;
            }
        });
        System.out.println(user);
    }
}

四、使⽤德鲁伊连接池

上面数据源是⽤我们⾃⼰写的。也可以使⽤别⼈写好的。例如⽐较⽜的德鲁伊连接池。

第⼀步:引⼊德鲁伊连接池的依赖。

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

第⼆步:将德鲁伊中的数据源配置到spring配置⽂件中。和配置我们⾃⼰写的⼀样。

<?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">

    <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:3306/spring6"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    

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

测试


public class SpringTest {
    @Test
    public void test(){
        // 获取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(?,?,?)";
        int count = jdbcTemplate.update(sql, null, "张三", 30);
        System.out.println("插⼊的记录条数:" + count);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/989960.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Vue.js 中的路由(Route)跳转

Vue.js 中的路由 官方解释 在 Vue.js 中&#xff0c;路由是一种用于导航和页面跳转的重要概念。Vue 提供了一个名为 Vue Router 的官方插件&#xff0c;用于构建单页面应用程序&#xff08;SPA&#xff09;的路由系统。Vue Router 允许您将不同的组件映射到应用程序的不同 URL…

​重生奇迹MU弓箭手PK路线​

定位远程物理输出的弓箭手职业&#xff0c;是很多女性玩家都比较喜欢的&#xff0c;操作难度非常低&#xff0c;其持续输出以及远距离攻击特性&#xff0c;都让她表现非常不错。 一般重生奇迹弓箭手在日常副本时都是选择堆输出&#xff0c;然后就是恢复能力。但是pk完全不一样…

【Spring面试】BeanFactory与IoC容器的加载

文章目录 Q1、BeanFactory的作用是什么&#xff1f;Q2、BeanDefinition的作用是什么&#xff1f;Q3、BeanFactory和ApplicationContext有什么区别&#xff1f;Q4、BeanFactory和FactoryBean有什么区别&#xff1f;Q5、说下Spring IoC容器的加载过程&#xff08;※&#xff09;Q…

自造简易版音频进度条

最近在做音乐播放器页面, 积累了很多有趣的经验, 今天先分享播放进度条的开发过程. 效果 话不多说&#xff0c;先看效果 支持点击修改进度&#xff0c;拖拽修改进度&#xff0c;当然大家肯定都知道ui库里面有现成的&#xff0c;为何要自己造一个 首先著名的ui库中确实都要这…

flask bootstrap页面json格式化

html <!DOCTYPE html> <html lang"en"> <head><!-- 新 Bootstrap5 核心 CSS 文件 --> <link rel"stylesheet" href"static/bootstrap-5.0.0-beta1-dist/css/bootstrap.min.css"><!-- 最新的 Bootstrap5 核心 …

C++ goto 语句

goto 语句允许把控制无条件转移到同一函数内的被标记的语句。 注意&#xff1a;在任何编程语言中&#xff0c;都不建议使用 goto 语句。因为它使得程序的控制流难以跟踪&#xff0c;使程序难以理解和难以修改。任何使用 goto 语句的程序可以改写成不需要使用 goto 语句的写法。…

【vue3】一些关于hooks的使用经验

前言 最近接到了一个需求&#xff0c;隔壁嵌入式部门希望我们用前端解析渲染Kconfig表单。这篇文章用来记录一下本次使用hook pinia vue3的经验 hooks hooks的概念最早是在 React 中听到的&#xff0c;虽然早些时间也写过一点react&#xff0c;但也只是照葫芦画瓢&#xf…

C++多线程编程(第四章 promise和future)

promise 和future promise用于异步传输变量 std::promise提供存储异步通信的值&#xff0c;再通过其对象创建的std::future异步获得结果。 std::promise只能使用一次。void set_value(_Ty&& _Val)设置传递值&#xff0c;只能调用一次std::future提供访问异步操作结果…

最新期权开户的形式有哪些?

期权目前都有哪些开户方式? 摘对于上证50etf期权的投资者来说,最关心的就是开户的问题了,而50etf期权开户方式目前主要有券商和平台开户两种,各有优缺点&#xff0c;下文介绍最新期权开户的形式有哪些&#xff1f; 一、最新的期权开户方式有多种&#xff0c;包括在线开户、手机…

自己的碎碎念集合

自己的碎碎念集合 2023-09-07 c叠加三目运算符闰年计算法2023-08-13 一个小题目 AB problem一、问题及解答关碍 总结 2023-07-26 C的2至36进制转换函数一、itoa()函数的示例代码总结 2023-07-19 平面坐标下判断三角形以及输出周长和面积一. 基本知识总结 2023-06-25 达芬奇去除…

认识伦敦银的真相,并没有那么容易

我们进行伦敦银投资&#xff0c;其实就是想利用一定的时间在这个市场中获取盈利。对于普通人来说&#xff0c;我们获得金钱的方法就是从事一份工作努力的&#xff0c;在这个职位中&#xff0c;做好自己的本职工作&#xff0c;最后老板为我们的辛勤付出&#xff0c;支付相应的工…

快速构建基于Paddle Serving部署的Paddle Detection目标检测Docker镜像

快速构建基于Paddle Serving部署的Paddle Detection目标检测Docker镜像 项目介绍需要重点关注的几个文件构建cpu版本的docker构建gpu版本的docker&#xff08;cuda11.2cudnn8&#xff09; 阅读提示&#xff1a; &#xff08;1&#xff09;Paddle的Serving项目中&#xff0c;在t…

OpenCV 06(图像的基本变换)

一、图像的基本变换 1.1 图像的放大与缩小 - resize(src, dsize, dst, fx, fy, interpolation) - src: 要缩放的图片 - dsize: 缩放之后的图片大小, 元组和列表表示均可. - dst: 可选参数, 缩放之后的输出图片 - fx, fy: x轴和y轴的缩放比, 即宽度和高度的缩放比. - …

【React学习】React高级特性

1. 函数式组件和类组件区别 函数式组件 函数式组件是一种简单的组件定义方式&#xff0c;它是一个以JavaScript函数为基础的组件。 可以把函数式组件理解为纯函数&#xff0c;它的输入为props&#xff0c;输出为JSX。函数式组件没有状态&#xff0c;也没有生命周期。 functio…

java特殊文件 属性文件properties和XML文件

属性文件properties 后缀为.properties的文件&#xff0c;称之为属性文件&#xff0c;它可以很方便的存储一些类似于键值对的数据。经常当做软件的配置文件使用。 首先我们要掌握属性文件的格式&#xff1a; 1.属性文件后缀以.properties结尾 2.属性文件里面的每一行都是一个…

Python Opencv实践 - Shi-Tomasi角点检测

参考资料&#xff1a;Harris和Shi-tomasi角点检测笔记&#xff08;详细推导&#xff09;_harris焦点检测_亦枫Leonlew的博客-CSDN博客 cv.goodFeaturesToTrack&#xff1a;Shi-Tomasi角点检测-OpenCV-python_独憩的博客-CSDN博客 import cv2 as cv import numpy as np import …

精准定位,智慧港口:北斗技术在港口车辆智能监管中的应用

随着全球经济一体化的加速推进&#xff0c;港口作为全球物流网络中的关键节点、对外贸易货物的集散中心以及国际物流供应链的重要组成部分&#xff0c;其在区域经济发展中的作用变得越来越重要。然而&#xff0c;随着港口向大型化、专业化方向的发展&#xff0c;现有的基础设施…

基于Java+SpringBoot+UniApp的微信小程序朋友圈

✌全网粉丝20W,csdn特邀作者、博客专家、CSDN新星计划导师、java领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取项目下载方式&#x1f345; 一、项目背景介绍&#xff1a; 随着社交媒体的兴起和…

在UE4虚幻引擎中加入导航网格体边界体积后丧尸不能移动和发现玩家

UE4系列文章目录 文章目录 UE4系列文章目录前言一、用到的知识点二、问题原因 前言 最近使用ue4做第一人称视角射击游戏发现问题&#xff0c;加入导航网格体边界体积后丧尸不能移动和发现玩家。下图是出现的问题图片 一、用到的知识点 1.行为树&#xff1a;控制并显示AI的决…

【后端面经-数据库】Redis数据结构和底层数据类型

【后端面经-数据库】Redis数据结构和底层数据类型 1. Redis数据类型1.1 基本数据类型1. string2. hash3. list4. set5. sortset/Zset 1.2 特殊数据类型1. bitmap2. hyperloglog3. GEO4. stream 2. Redis底层数据类型2.1 简介2.2 动态字符串SDS2.3 快表QuickList2.4 字典Dict2.5…