当前位置: 首页 > 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;也可以在编译类时自动…...

未来机器人的大脑:如何用神经网络模拟器实现更智能的决策?

编辑&#xff1a;陈萍萍的公主一点人工一点智能 未来机器人的大脑&#xff1a;如何用神经网络模拟器实现更智能的决策&#xff1f;RWM通过双自回归机制有效解决了复合误差、部分可观测性和随机动力学等关键挑战&#xff0c;在不依赖领域特定归纳偏见的条件下实现了卓越的预测准…...

Opencv中的addweighted函数

一.addweighted函数作用 addweighted&#xff08;&#xff09;是OpenCV库中用于图像处理的函数&#xff0c;主要功能是将两个输入图像&#xff08;尺寸和类型相同&#xff09;按照指定的权重进行加权叠加&#xff08;图像融合&#xff09;&#xff0c;并添加一个标量值&#x…...

【机器视觉】单目测距——运动结构恢复

ps&#xff1a;图是随便找的&#xff0c;为了凑个封面 前言 在前面对光流法进行进一步改进&#xff0c;希望将2D光流推广至3D场景流时&#xff0c;发现2D转3D过程中存在尺度歧义问题&#xff0c;需要补全摄像头拍摄图像中缺失的深度信息&#xff0c;否则解空间不收敛&#xf…...

页面渲染流程与性能优化

页面渲染流程与性能优化详解&#xff08;完整版&#xff09; 一、现代浏览器渲染流程&#xff08;详细说明&#xff09; 1. 构建DOM树 浏览器接收到HTML文档后&#xff0c;会逐步解析并构建DOM&#xff08;Document Object Model&#xff09;树。具体过程如下&#xff1a; (…...

Nuxt.js 中的路由配置详解

Nuxt.js 通过其内置的路由系统简化了应用的路由配置&#xff0c;使得开发者可以轻松地管理页面导航和 URL 结构。路由配置主要涉及页面组件的组织、动态路由的设置以及路由元信息的配置。 自动路由生成 Nuxt.js 会根据 pages 目录下的文件结构自动生成路由配置。每个文件都会对…...

UR 协作机器人「三剑客」:精密轻量担当(UR7e)、全能协作主力(UR12e)、重型任务专家(UR15)

UR协作机器人正以其卓越性能在现代制造业自动化中扮演重要角色。UR7e、UR12e和UR15通过创新技术和精准设计满足了不同行业的多样化需求。其中&#xff0c;UR15以其速度、精度及人工智能准备能力成为自动化领域的重要突破。UR7e和UR12e则在负载规格和市场定位上不断优化&#xf…...

【HarmonyOS 5 开发速记】如何获取用户信息(头像/昵称/手机号)

1.获取 authorizationCode&#xff1a; 2.利用 authorizationCode 获取 accessToken&#xff1a;文档中心 3.获取手机&#xff1a;文档中心 4.获取昵称头像&#xff1a;文档中心 首先创建 request 若要获取手机号&#xff0c;scope必填 phone&#xff0c;permissions 必填 …...

是否存在路径(FIFOBB算法)

题目描述 一个具有 n 个顶点e条边的无向图&#xff0c;该图顶点的编号依次为0到n-1且不存在顶点与自身相连的边。请使用FIFOBB算法编写程序&#xff0c;确定是否存在从顶点 source到顶点 destination的路径。 输入 第一行两个整数&#xff0c;分别表示n 和 e 的值&#xff08;1…...

LeetCode - 199. 二叉树的右视图

题目 199. 二叉树的右视图 - 力扣&#xff08;LeetCode&#xff09; 思路 右视图是指从树的右侧看&#xff0c;对于每一层&#xff0c;只能看到该层最右边的节点。实现思路是&#xff1a; 使用深度优先搜索(DFS)按照"根-右-左"的顺序遍历树记录每个节点的深度对于…...

处理vxe-table 表尾数据是单独一个接口,表格tableData数据更新后,需要点击两下,表尾才是正确的

修改bug思路&#xff1a; 分别把 tabledata 和 表尾相关数据 console.log() 发现 更新数据先后顺序不对 settimeout延迟查询表格接口 ——测试可行 升级↑&#xff1a;async await 等接口返回后再开始下一个接口查询 ________________________________________________________…...