当前位置: 首页 > news >正文

Spring系列文章:Spring使用JdbcTemplate

一、简介

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对象就⾏。其他⽅法不⽤管。@Overridepublic Connection getConnection() throws SQLException {try {Class.forName(driver);Connection conn = DriverManager.getConnection(url, username, password);return conn;} catch (Exception e) {e.printStackTrace();}return null;}@Overridepublic Connection getConnection(String username, String password) throws SQLException {return null;}@Overridepublic PrintWriter getLogWriter() throws SQLException {return null;}@Overridepublic void setLogWriter(PrintWriter out) throws SQLException {}@Overridepublic void setLoginTimeout(int seconds) throws SQLException {}@Overridepublic int getLoginTimeout() throws SQLException {return 0;}@Overridepublic Logger getParentLogger() throws SQLFeatureNotSupportedException {return null;}@Overridepublic <T> T unwrap(Class<T> iface) throws SQLException {return null;}@Overridepublic 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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://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 {@Testpublic 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 {@Testpublic 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 {@Testpublic void test(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);// 执⾏deleteString sql = "delete from t_user where id = ?";int count = jdbcTemplate.update(sql, 1);System.out.println("删除了⼏条记录:" + count);}
}

4、查询一个对象

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

7、批量添加

public class SpringTest {@Testpublic 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 {@Testpublic 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 {@Testpublic 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 {@Testpublic 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>() {@Overridepublic 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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://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 {@Testpublic 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);}
}

相关文章:

Spring系列文章:Spring使用JdbcTemplate

一、简介 JdbcTemplate是Spring提供的⼀个JDBC模板类&#xff0c;是对JDBC的封装&#xff0c;简化JDBC代码。 当然&#xff0c;你也可以不⽤&#xff0c;可以让Spring集成其它的ORM框架&#xff0c;例如&#xff1a;MyBatis、Hibernate等。 第一步&#xff1a;引入依赖 <d…...

[matlab]cvx安装后测试代码

测试环境&#xff1a; windows10 x64 matlab2023a 代码来自官方网站&#xff1a;CVX: Matlab Software for Disciplined Convex Programming | CVX Research, Inc. m 20; n 10; p 4; A randn(m,n); b randn(m,1); C randn(p,n); d randn(p,1); e rand; cvx_beginva…...

【css】margin:auot什么情况下失效

margin&#xff1a;auto只对块级元素有效果&#xff0c;并且在正常文档流margin&#xff1a;automargin&#xff1a;0 auto&#xff0c;css默认在正常文档流里面margin-top和margin-bottom是0 为什么margin: auto能实现水平居中&#xff0c;而垂直居中不行&#xff1f; 一般子…...

linux的dirty page回写磁盘过程中是否允许并发写入更新page?

概述 众所周知Linux内核write系统调用采用pagecache机制加速写入过程,避免write系统调用长时间block应用进程,用户态进程执行write调用的时候,内核只是将用户态buffer copy到内核的pagecache当中,write系统调用就返回了,完全不需要等待数据完全写入存储设备,因为存储设备…...

Docker-基础命令使用

文章目录 前言命令帮助命令执行示意图docker rundocker psdocker inspectdocker execdocker attachdocker stopdocker startdocker topdocker rmdocker prune参考说明 前言 本文主要介绍Docker基础命令的使用方法。 命令帮助 Docker命令获取帮助方法 # docker -h Flag shor…...

【Python 程序设计】Python 中的类型提示【06/8】

目录 一、说明 二、什么是动态类型&#xff1f; 2.1 为什么要使用类型提示&#xff1f; 2.2 局限性 三、基本类型提示 3.1 声明变量的类型 3.2 函数注释 四、Python 中的内置类型 4.1 原子类型与复合类型 五、函数注释 5.1 如何指定函数的参数类型和返回类型 5.2 在函数签名中…...

78 # koa 中间件的实现

上上节实现了上下文的&#xff0c;上一节使用了一下中间件&#xff0c;这一节来实现 koa 的中间件这个洋葱模型。 思路&#xff1a; 储存用户所有的 callback将用户传递的 callback 全部组合起来&#xff08;redux 里的 compose&#xff09;组合成一个线性结构依次执行&#…...

国产操作系统麒麟v10中遇到的一些问题

下载pycharm&#xff1a;直接在应用商店 目标&#xff1a;主机1安装了虚拟机&#xff0c;主机2要ping通主机1安装的虚拟机。 前提&#xff1a;主机1&#xff0c;主机2在同一局域网下&#xff0c;同一网段。 网络配置 因为虚拟机的网段不在局域网网段内&#xff0c;局域网下…...

Gridea+GitPage+Gittalk 搭建个人博客

&#x1f44b;通过GrideaGitPage 搭建属于自己的博客&#xff01; &#x1f47b;GitPage 负责提供 Web 功能&#xff01; &#x1f63d;Gridea 作为本地编辑器&#xff0c;方便 push 文章&#xff01; &#x1f3f7;本文讲解如何使用 GrideaGitPage 服务域名&#xff08;可选&a…...

代码质量保障第2讲:单元测试 - 浅谈单元测试

代码质量保障第2讲&#xff1a;单元测试 - 浅谈单元测试 本文是代码质量保障第2讲&#xff0c;浅谈单元测试。单元测试&#xff08;unit testing&#xff09;&#xff0c;是指对软件中的最小可测试单元进行检查和验证。这是基础&#xff0c;所以围绕着单元测试&#xff0c;我从…...

“五度晟企通”企业发展服务平台正式发布,帮扶企业行稳致远!

在数字中国建设的大背景下&#xff0c;“五度易链”以企业实际发展需求为牵引&#xff0c;以帮扶企业行稳致远为目标&#xff0c;基于全体量产业大数据&#xff0c;运用NLP、AI等新一代信息技术&#xff0c;打造了数字化ToB企业发展服务平台“五度晟企通”&#xff0c;旨在以数…...

Java类和对象(七千字详解!!!带你彻底理解类和对象)

目录 一、面向对象的初步认知 1、什么是面向对象 2、面向对象和面向过程 &#xff08;1&#xff09;传统洗衣服的过程 &#xff08;2&#xff09;现代洗衣服过程 ​编辑 二、类的定义和使用 1、类的定义格式 三、类的实例化 1、什么是实例化 2、类和对象说明 四、t…...

机器学习笔记:node2vec(论文笔记:node2vec: Scalable Feature Learning for Networks)

2016 KDD 1 intro 利用graph上的节点相似性&#xff0c;对这些节点进行embedding 同质性&#xff1a;节点和其周围节点的embedding比较相似 蓝色节点和其周围的节点结构等价性 结构相近的点embedding相近 比如蓝色节点&#xff0c;都处于多个簇的连接处 2 随机游走 2.1 介绍…...

go基础10 -字符串的高效构造与转换

前面提到过&#xff0c;Go原生支持通过/操作符来连接多个字符串以构造一个更长的字符串&#xff0c;并且通过/操作符的字符串连接构造是最自然、开发体验最好的一种。 但Go还提供了其他一些构造字符串的方法&#xff0c;比如&#xff1a; ● 使用fmt.Sprintf&#xff1b; ● 使…...

VR钢铁实训 | 铁前事业部虚拟仿真培训软件

随着科技的发展&#xff0c;虚拟现实技术在各个行业中的应用越来越广泛。在钢铁冶炼行业中&#xff0c;VR技术也逐渐得到了应用&#xff0c;其中铁前事业部虚拟仿真培训软件就是一项非常有优势的技术。 铁前事业部虚拟仿真培训软件是广州华锐互动打造的《钢铁生产VR虚拟培训系统…...

DevOps

DevOps 是开发 (Dev) 和运营 (Ops) 的复合词&#xff0c;它将人、流程和技术结合起来&#xff0c;不断地为客户提供价值。 DevOps 对团队意味着什么&#xff1f; DevOps 使以前孤立的角色&#xff08;开发、IT 运营、质量工程和安全&#xff09;可以协调和协作&#xff0c;以生…...

IJ中PHP环境的搭建和使用教程

目录 目录 前言 思维导图 1&#xff0c;PHP环境下载 1.下载链接 2.进行安装 3,自定义路径 4.进行相关的一些库的选择下载 2&#xff0c;进行IJ中PHP环境的配置 2.1,下载PHP插件 2.2,下载过程中的注意事项 3&#xff0c;为什么这么做呢? 3.1,原因 3.2,进行代码…...

java开发之个人微信的二次开发

简要描述&#xff1a; 修改我在某群的昵称 请求URL&#xff1a; http://域名/updateIInChatRoomNickName 请求方式&#xff1a; POST 请求头Headers&#xff1a; Content-Type&#xff1a;application/jsonAuthorization&#xff1a;login接口返回 参数&#xff1a; 参…...

ISYSTEM调试实践11-Profiler Timeline和软件运行时间分析

一 前言 本文主要内容是讨论嵌入式软件的时间分析&#xff0c;供大家探讨&#xff0c;如果有疑问欢迎探讨。 对于汽车软件&#xff0c;往往对执行的时序和代码运行的时间有着严格要求。对于在主循环内执行的任务函数&#xff0c;不论是手写还是Autosar生成,能否节拍执行到&…...

第十八章 ObjectScript - 使用例程

文章目录 第十八章 ObjectScript - 使用例程例程Procedures, Functions, and Subroutines 过程、函数和子程序procedurefunctionsubroutine 第十八章 ObjectScript - 使用例程 例程 可以将例程视为 ObjectScript 程序。例程可以从头开始编写&#xff0c;也可以在编译类时自动…...

CTF show Web 红包题第六弹

提示 1.不是SQL注入 2.需要找关键源码 思路 进入页面发现是一个登录框&#xff0c;很难让人不联想到SQL注入&#xff0c;但提示都说了不是SQL注入&#xff0c;所以就不往这方面想了 ​ 先查看一下网页源码&#xff0c;发现一段JavaScript代码&#xff0c;有一个关键类ctfs…...

中南大学无人机智能体的全面评估!BEDI:用于评估无人机上具身智能体的综合性基准测试

作者&#xff1a;Mingning Guo, Mengwei Wu, Jiarun He, Shaoxian Li, Haifeng Li, Chao Tao单位&#xff1a;中南大学地球科学与信息物理学院论文标题&#xff1a;BEDI: A Comprehensive Benchmark for Evaluating Embodied Agents on UAVs论文链接&#xff1a;https://arxiv.…...

遍历 Map 类型集合的方法汇总

1 方法一 先用方法 keySet() 获取集合中的所有键。再通过 gey(key) 方法用对应键获取值 import java.util.HashMap; import java.util.Set;public class Test {public static void main(String[] args) {HashMap hashMap new HashMap();hashMap.put("语文",99);has…...

九天毕昇深度学习平台 | 如何安装库?

pip install 库名 -i https://pypi.tuna.tsinghua.edu.cn/simple --user 举个例子&#xff1a; 报错 ModuleNotFoundError: No module named torch 那么我需要安装 torch pip install torch -i https://pypi.tuna.tsinghua.edu.cn/simple --user pip install 库名&#x…...

Web中间件--tomcat学习

Web中间件–tomcat Java虚拟机详解 什么是JAVA虚拟机 Java虚拟机是一个抽象的计算机&#xff0c;它可以执行Java字节码。Java虚拟机是Java平台的一部分&#xff0c;Java平台由Java语言、Java API和Java虚拟机组成。Java虚拟机的主要作用是将Java字节码转换为机器代码&#x…...

在golang中如何将已安装的依赖降级处理,比如:将 go-ansible/v2@v2.2.0 更换为 go-ansible/@v1.1.7

在 Go 项目中降级 go-ansible 从 v2.2.0 到 v1.1.7 具体步骤&#xff1a; 第一步&#xff1a; 修改 go.mod 文件 // 原 v2 版本声明 require github.com/apenella/go-ansible/v2 v2.2.0 替换为&#xff1a; // 改为 v…...

uni-app学习笔记三十五--扩展组件的安装和使用

由于内置组件不能满足日常开发需要&#xff0c;uniapp官方也提供了众多的扩展组件供我们使用。由于不是内置组件&#xff0c;需要安装才能使用。 一、安装扩展插件 安装方法&#xff1a; 1.访问uniapp官方文档组件部分&#xff1a;组件使用的入门教程 | uni-app官网 点击左侧…...

Appium下载安装配置保姆教程(图文详解)

目录 一、Appium软件介绍 1.特点 2.工作原理 3.应用场景 二、环境准备 安装 Node.js 安装 Appium 安装 JDK 安装 Android SDK 安装Python及依赖包 三、安装教程 1.Node.js安装 1.1.下载Node 1.2.安装程序 1.3.配置npm仓储和缓存 1.4. 配置环境 1.5.测试Node.j…...

VSCode 使用CMake 构建 Qt 5 窗口程序

首先,目录结构如下图: 运行效果: cmake -B build cmake --build build 运行: windeployqt.exe F:\testQt5\build\Debug\app.exe main.cpp #include "mainwindow.h"#include <QAppli...

Qt Quick Controls模块功能及架构

Qt Quick Controls是Qt Quick的一个附加模块&#xff0c;提供了一套用于构建完整用户界面的UI控件。在Qt 6.0中&#xff0c;这个模块经历了重大重构和改进。 一、主要功能和特点 1. 架构重构 完全重写了底层架构&#xff0c;与Qt Quick更紧密集成 移除了对Qt Widgets的依赖&…...