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

Java 语言特性(面试系列2)

一、SQL 基础 1. 复杂查询 &#xff08;1&#xff09;连接查询&#xff08;JOIN&#xff09; 内连接&#xff08;INNER JOIN&#xff09;&#xff1a;返回两表匹配的记录。 SELECT e.name, d.dept_name FROM employees e INNER JOIN departments d ON e.dept_id d.dept_id; 左…...

地震勘探——干扰波识别、井中地震时距曲线特点

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

超短脉冲激光自聚焦效应

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

51c自动驾驶~合集58

我自己的原文哦~ https://blog.51cto.com/whaosoft/13967107 #CCA-Attention 全局池化局部保留&#xff0c;CCA-Attention为LLM长文本建模带来突破性进展 琶洲实验室、华南理工大学联合推出关键上下文感知注意力机制&#xff08;CCA-Attention&#xff09;&#xff0c;…...

Spring Boot面试题精选汇总

&#x1f91f;致敬读者 &#x1f7e9;感谢阅读&#x1f7e6;笑口常开&#x1f7ea;生日快乐⬛早点睡觉 &#x1f4d8;博主相关 &#x1f7e7;博主信息&#x1f7e8;博客首页&#x1f7eb;专栏推荐&#x1f7e5;活动信息 文章目录 Spring Boot面试题精选汇总⚙️ **一、核心概…...

今日科技热点速览

&#x1f525; 今日科技热点速览 &#x1f3ae; 任天堂Switch 2 正式发售 任天堂新一代游戏主机 Switch 2 今日正式上线发售&#xff0c;主打更强图形性能与沉浸式体验&#xff0c;支持多模态交互&#xff0c;受到全球玩家热捧 。 &#x1f916; 人工智能持续突破 DeepSeek-R1&…...

自然语言处理——循环神经网络

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

微软PowerBI考试 PL300-在 Power BI 中清理、转换和加载数据

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

Mysql中select查询语句的执行过程

目录 1、介绍 1.1、组件介绍 1.2、Sql执行顺序 2、执行流程 2.1. 连接与认证 2.2. 查询缓存 2.3. 语法解析&#xff08;Parser&#xff09; 2.4、执行sql 1. 预处理&#xff08;Preprocessor&#xff09; 2. 查询优化器&#xff08;Optimizer&#xff09; 3. 执行器…...

uniapp 字符包含的相关方法

在uniapp中&#xff0c;如果你想检查一个字符串是否包含另一个子字符串&#xff0c;你可以使用JavaScript中的includes()方法或者indexOf()方法。这两种方法都可以达到目的&#xff0c;但它们在处理方式和返回值上有所不同。 使用includes()方法 includes()方法用于判断一个字…...