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模板类,是对JDBC的封装,简化JDBC代码。 当然,你也可以不⽤,可以让Spring集成其它的ORM框架,例如:MyBatis、Hibernate等。 第一步:引入依赖 <d…...
[matlab]cvx安装后测试代码
测试环境: windows10 x64 matlab2023a 代码来自官方网站: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:auto只对块级元素有效果,并且在正常文档流margin:automargin:0 auto,css默认在正常文档流里面margin-top和margin-bottom是0 为什么margin: auto能实现水平居中,而垂直居中不行? 一般子…...
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】
目录 一、说明 二、什么是动态类型? 2.1 为什么要使用类型提示? 2.2 局限性 三、基本类型提示 3.1 声明变量的类型 3.2 函数注释 四、Python 中的内置类型 4.1 原子类型与复合类型 五、函数注释 5.1 如何指定函数的参数类型和返回类型 5.2 在函数签名中…...

78 # koa 中间件的实现
上上节实现了上下文的,上一节使用了一下中间件,这一节来实现 koa 的中间件这个洋葱模型。 思路: 储存用户所有的 callback将用户传递的 callback 全部组合起来(redux 里的 compose)组合成一个线性结构依次执行&#…...
国产操作系统麒麟v10中遇到的一些问题
下载pycharm:直接在应用商店 目标:主机1安装了虚拟机,主机2要ping通主机1安装的虚拟机。 前提:主机1,主机2在同一局域网下,同一网段。 网络配置 因为虚拟机的网段不在局域网网段内,局域网下…...

Gridea+GitPage+Gittalk 搭建个人博客
👋通过GrideaGitPage 搭建属于自己的博客! 👻GitPage 负责提供 Web 功能! 😽Gridea 作为本地编辑器,方便 push 文章! 🏷本文讲解如何使用 GrideaGitPage 服务域名(可选&a…...
代码质量保障第2讲:单元测试 - 浅谈单元测试
代码质量保障第2讲:单元测试 - 浅谈单元测试 本文是代码质量保障第2讲,浅谈单元测试。单元测试(unit testing),是指对软件中的最小可测试单元进行检查和验证。这是基础,所以围绕着单元测试,我从…...

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

Java类和对象(七千字详解!!!带你彻底理解类和对象)
目录 一、面向对象的初步认知 1、什么是面向对象 2、面向对象和面向过程 (1)传统洗衣服的过程 (2)现代洗衣服过程 编辑 二、类的定义和使用 1、类的定义格式 三、类的实例化 1、什么是实例化 2、类和对象说明 四、t…...

机器学习笔记:node2vec(论文笔记:node2vec: Scalable Feature Learning for Networks)
2016 KDD 1 intro 利用graph上的节点相似性,对这些节点进行embedding 同质性:节点和其周围节点的embedding比较相似 蓝色节点和其周围的节点结构等价性 结构相近的点embedding相近 比如蓝色节点,都处于多个簇的连接处 2 随机游走 2.1 介绍…...
go基础10 -字符串的高效构造与转换
前面提到过,Go原生支持通过/操作符来连接多个字符串以构造一个更长的字符串,并且通过/操作符的字符串连接构造是最自然、开发体验最好的一种。 但Go还提供了其他一些构造字符串的方法,比如: ● 使用fmt.Sprintf; ● 使…...

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

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

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

java开发之个人微信的二次开发
简要描述: 修改我在某群的昵称 请求URL: http://域名/updateIInChatRoomNickName 请求方式: POST 请求头Headers: Content-Type:application/jsonAuthorization:login接口返回 参数: 参…...

ISYSTEM调试实践11-Profiler Timeline和软件运行时间分析
一 前言 本文主要内容是讨论嵌入式软件的时间分析,供大家探讨,如果有疑问欢迎探讨。 对于汽车软件,往往对执行的时序和代码运行的时间有着严格要求。对于在主循环内执行的任务函数,不论是手写还是Autosar生成,能否节拍执行到&…...
第十八章 ObjectScript - 使用例程
文章目录 第十八章 ObjectScript - 使用例程例程Procedures, Functions, and Subroutines 过程、函数和子程序procedurefunctionsubroutine 第十八章 ObjectScript - 使用例程 例程 可以将例程视为 ObjectScript 程序。例程可以从头开始编写,也可以在编译类时自动…...
Java 语言特性(面试系列2)
一、SQL 基础 1. 复杂查询 (1)连接查询(JOIN) 内连接(INNER JOIN):返回两表匹配的记录。 SELECT e.name, d.dept_name FROM employees e INNER JOIN departments d ON e.dept_id d.dept_id; 左…...

地震勘探——干扰波识别、井中地震时距曲线特点
目录 干扰波识别反射波地震勘探的干扰波 井中地震时距曲线特点 干扰波识别 有效波:可以用来解决所提出的地质任务的波;干扰波:所有妨碍辨认、追踪有效波的其他波。 地震勘探中,有效波和干扰波是相对的。例如,在反射波…...

超短脉冲激光自聚焦效应
前言与目录 强激光引起自聚焦效应机理 超短脉冲激光在脆性材料内部加工时引起的自聚焦效应,这是一种非线性光学现象,主要涉及光学克尔效应和材料的非线性光学特性。 自聚焦效应可以产生局部的强光场,对材料产生非线性响应,可能…...

51c自动驾驶~合集58
我自己的原文哦~ https://blog.51cto.com/whaosoft/13967107 #CCA-Attention 全局池化局部保留,CCA-Attention为LLM长文本建模带来突破性进展 琶洲实验室、华南理工大学联合推出关键上下文感知注意力机制(CCA-Attention),…...
Spring Boot面试题精选汇总
🤟致敬读者 🟩感谢阅读🟦笑口常开🟪生日快乐⬛早点睡觉 📘博主相关 🟧博主信息🟨博客首页🟫专栏推荐🟥活动信息 文章目录 Spring Boot面试题精选汇总⚙️ **一、核心概…...
今日科技热点速览
🔥 今日科技热点速览 🎮 任天堂Switch 2 正式发售 任天堂新一代游戏主机 Switch 2 今日正式上线发售,主打更强图形性能与沉浸式体验,支持多模态交互,受到全球玩家热捧 。 🤖 人工智能持续突破 DeepSeek-R1&…...

自然语言处理——循环神经网络
自然语言处理——循环神经网络 循环神经网络应用到基于机器学习的自然语言处理任务序列到类别同步的序列到序列模式异步的序列到序列模式 参数学习和长程依赖问题基于门控的循环神经网络门控循环单元(GRU)长短期记忆神经网络(LSTM)…...

微软PowerBI考试 PL300-在 Power BI 中清理、转换和加载数据
微软PowerBI考试 PL300-在 Power BI 中清理、转换和加载数据 Power Query 具有大量专门帮助您清理和准备数据以供分析的功能。 您将了解如何简化复杂模型、更改数据类型、重命名对象和透视数据。 您还将了解如何分析列,以便知晓哪些列包含有价值的数据,…...

Mysql中select查询语句的执行过程
目录 1、介绍 1.1、组件介绍 1.2、Sql执行顺序 2、执行流程 2.1. 连接与认证 2.2. 查询缓存 2.3. 语法解析(Parser) 2.4、执行sql 1. 预处理(Preprocessor) 2. 查询优化器(Optimizer) 3. 执行器…...
uniapp 字符包含的相关方法
在uniapp中,如果你想检查一个字符串是否包含另一个子字符串,你可以使用JavaScript中的includes()方法或者indexOf()方法。这两种方法都可以达到目的,但它们在处理方式和返回值上有所不同。 使用includes()方法 includes()方法用于判断一个字…...