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

Spring框架 - JDBC模板技术

传统的JDBC传统JDBC的操作1. 注册驱动Class.forName(com.mysql.jdbc.Driver);2. 获取连接conn DriverManager.getConnection(jdbc:mysql://localhost:3306/test, root, password);3. 创建PreparedStatementString sql SELECT * FROM account WHERE id ?;ps conn.prepareStatement(sql);ps.setInt(1, id);4. 执行查询rs ps.executeQuery();5. 结果集处理if (rs.next()) { account new Account(); account.setId(rs.getInt(id)); account.setName(rs.getString(name)); account.setMoney(rs.getDouble(money)); }6. 关闭资源if (rs ! null) rs.close();if (ps ! null) ps.close();if (conn ! null) conn.close();JDBC模板JDBC模板JdbcTemplate是Spring框架提供的一个类它简化了传统的JDBC操作封装了JDBC的样板代码让开发者可以更专注于SQL语句和业务逻辑。传统JDBC的问题代码冗余每次操作都要重复连接、语句、结果集处理资源管理繁琐必须手动关闭连接Connection、Statement、结果集ResultSet异常处理复杂事务管理困难需要手动控制事务易出错资源泄露、空指针异常等JDBC模板的优势极大的简化代码自动资源管理jdbcTemplate.query(sql, rowMapper, params);统一异常处理jdbcTemplate.update(sql, params);方便事务管理这就是为什么是要JDBC模板的原因。JDBC模板的使用 - new对象的方式1. 创建maven Java项目2. 引入依赖dependencies dependency !--Spring依赖-- groupIdorg.springframework/groupId artifactIdspring-context/artifactId version5.0.2.RELEASE/version /dependency !--日志依赖-- dependency groupIdcommons-logging/groupId artifactIdcommons-logging/artifactId version1.2/version /dependency dependency groupIdlog4j/groupId artifactIdlog4j/artifactId version1.2.12/version /dependency !--单元测试的环境-- dependency groupIdjunit/groupId artifactIdjunit/artifactId version4.12/version scopetest/scope /dependency !-- Spring整合Junit测试的jar包 -- dependency groupIdorg.springframework/groupId artifactIdspring-test/artifactId version5.0.2.RELEASE/version scopetest/scope /dependency !-- AOP联盟 -- dependency groupIdaopalliance/groupId artifactIdaopalliance/artifactId version1.0/version /dependency !-- Spring Aspects -- dependency groupIdorg.springframework/groupId artifactIdspring-aspects/artifactId version5.0.2.RELEASE/version /dependency !-- aspectj -- dependency groupIdorg.aspectj/groupId artifactIdaspectjweaver/artifactId version1.8.3/version /dependency !-- mysql驱动包 -- dependency groupIdmysql/groupId artifactIdmysql-connector-java/artifactId version5.1.6/version /dependency dependency groupIdorg.springframework/groupId artifactIdspring-jdbc/artifactId version5.0.2.RELEASE/version /dependency dependency groupIdorg.springframework/groupId artifactIdspring-tx/artifactId version5.0.2.RELEASE/version /dependency /dependencies3. 使用new对象的方式编写测试代码package com.qcby.test; import com.qcby.model.BeanMapper; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; public class test1 { Test /** * 使用new对象方式创建 */ public void run(){ // 创建连接池对象Spring框架内设置了连接池对象 DriverManagerDataSource ds new DriverManagerDataSource(); // 设置4个参数 ds.setDriverClassName(com.mysql.jdbc.Driver); ds.setUrl(jdbc:mysql:///spring_db); ds.setUsername(root); ds.setPassword(root); // 提供模板创建对象 JdbcTemplate template new JdbcTemplate(ds); // 插入数据 template.update(insert into account values (null,?,?),悠悠,10000); // 修改数据 template.update(update account set money ? WHERE name ?,10000,喜羊羊); // 删除数据 template.update(delete from account where id ?,14); // 根据id查询 template.queryForObject(select * from account where id ?,new BeanMapper(),13); } }Spring框架管理JDBC模板将DataSource、参数、JDBCTemplate交由Spring框架的IOC容器管理。1. 编写配置文件applicationContext.xml?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beans xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd !--配置Spring框架内置的连接池-- bean idds classorg.springframework.jdbc.datasource.DriverManagerDataSource property namedriverClassName valuecom.mysql.jdbc.Driver/property property nameurl valuejdbc:mysql:///spring_db/property property nameusername valueroot/property property namepassword valueroot/property /bean !--配置jdbc模板-- bean idjdbcTemplate classorg.springframework.jdbc.core.JdbcTemplate property namedataSource refds/property /bean /beans2. 编写测试类package com.qcby.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * 使用Spring框架内置的连接池 */ RunWith(SpringJUnit4ClassRunner.class) ContextConfiguration(classpath:applicationContext.xml) public class test2 { Autowired private JdbcTemplate jdbcTemplate; Test public void run(){ jdbcTemplate.update(insert into account values (null,?,?),筱悠,10000); } }Spring框架管理开源的连接池 - Druid连接池1. 引入Druid的依赖dependency groupIdcom.alibaba/groupId artifactIddruid/artifactId version1.1.10/version /dependency2. 将数据库连接的信息配置道属性文件jdbc.peopertiesjdbc.driverClassNamecom.mysql.jdbc.Driver jdbc.urljdbc:mysql:///spring_db jdbc.usernameroot jdbc.passwordroot3. 编写配置文件applicationContext_jdbc.xml?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beans xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xmlns:contexthttp://www.springframework.org/schema/context xsi:schemaLocationhttp://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 !--使用标签方式-- context:property-placeholder locationclasspath:jdbc.properties/context:property-placeholder !--加载属性文件-- bean iddataSource classcom.alibaba.druid.pool.DruidDataSource property namedriverClassName value${jdbc.driverClassName} / property nameurl value${jdbc.url} / property nameusername value${jdbc.username} / property namepassword value${jdbc.password} / /bean !--配置jdbc模板-- bean idjdbcTemplate classorg.springframework.jdbc.core.JdbcTemplate property namedataSource refdataSource/property /bean /beans4. 编写BeanMapper类package com.qcby.model; import org.springframework.jdbc.core.RowMapper; import java.sql.ResultSet; import java.sql.SQLException; // 实现类用来进行数据封装 public class BeanMapper implements RowMapperAccount { /** * 是一行一行进行数据封装的 * param resultSet 查询结果集 * param i 行 * return * throws SQLException */ Override public Account mapRow(ResultSet resultSet, int i) throws SQLException { Account account new Account(); account.setId(resultSet.getInt(id)); account.setName(resultSet.getString(name)); account.setMoney(resultSet.getDouble(money)); return account; } }5. 编写测试类package com.qcby.test; import com.qcby.model.Account; import com.qcby.model.BeanMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; RunWith(SpringJUnit4ClassRunner.class) ContextConfiguration(classpath:applicationContext_jdbc.xml) public class test3 { Autowired private JdbcTemplate jdbcTemplate; // 添加 Test public void add(){ jdbcTemplate.update(insert into account values (null,?,?),狸夏,10000); } // 修改 Test public void update(){ jdbcTemplate.update(update account set name ?, money ? where id ?,村长,10000,7); } // 删除 Test public void delete(){ jdbcTemplate.update(delete from account where id ?, 8); } // 查询 - 通过id查询 Test public void query(){ Account account jdbcTemplate.queryForObject(select * from account where id ?,new BeanMapper(),6); System.out.println(account); } // 查询所有数据 Test public void queryAll(){ ListAccount list jdbcTemplate.query(select * from account,new BeanMapper()); for (Account account:list){ System.out.println(account); } } }

相关文章:

Spring框架 - JDBC模板技术

传统的JDBC传统JDBC的操作1. 注册驱动:Class.forName("com.mysql.jdbc.Driver");2. 获取连接:conn DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");3. 创建PreparedSt…...

MCP 2026权限动态分配:如何用1个策略模板+2个API+4类上下文信号,实现毫秒级权限决策?

更多请点击: https://intelliparadigm.com 第一章:MCP 2026权限动态分配:架构演进与核心价值 MCP 2026(Multi-Context Permissioning 2026)代表了企业级权限模型的一次范式跃迁——从静态 RBAC 向上下文感知、策略驱动…...

RTIC在RISC-V平台上的应用:ESP32C3和ESP32C6完整开发教程

RTIC在RISC-V平台上的应用:ESP32C3和ESP32C6完整开发教程 【免费下载链接】rtic Real-Time Interrupt-driven Concurrency (RTIC) framework for ARM Cortex-M microcontrollers 项目地址: https://gitcode.com/gh_mirrors/rt/rtic Real-Time Interrupt-driv…...

Semantic Kernel 在企业级 Harness 开发中的应用

Semantic Kernel 在企业级 Harness 开发中的应用:打造 AI 原生的内部开发平台(IDP) 摘要 随着企业数字化转型的深入,云原生CI/CD平台Harness已经成为众多中大型企业构建内部开发平台(IDP)的首选方案,但Harness的YAML编排复杂度高、排障耗时久、自定义扩展门槛高、知识…...

机器学习中的CASH优化:算法选择与超参调优一体化

1. CASH优化问题本质解析在机器学习项目实践中,我们常面临双重挑战:既要选择合适的算法,又要调整该算法的超参数。传统做法是将这两个环节割裂处理,先凭经验选定算法再调参,这种人为分割往往导致次优结果。CASH&#x…...

3步解锁Switch Joy-Con手柄在Windows的完整潜力:JoyCon-Driver实战指南

3步解锁Switch Joy-Con手柄在Windows的完整潜力:JoyCon-Driver实战指南 【免费下载链接】JoyCon-Driver A vJoy feeder for the Nintendo Switch JoyCons and Pro Controller 项目地址: https://gitcode.com/gh_mirrors/jo/JoyCon-Driver 想要让闲置的Switch…...

AIGC检测原理是什么?看完就知道为什么你的论文AI这么高!

2026年答辩季临近,AIGC检测已经成为大多数高校论文审核的标配流程。不管你有没有用过A论文,学校都可能会查一遍AI率。很多同学的第一反应就是:ai率查重要多少钱?有没有能免费查AI率的工具? 有免费的aigc检测工具&…...

Kimi/DeepSeek写论文AIGC率为什么高?AI写论文降AIGC率全攻略告诉你!

2026年答辩季临近,AIGC检测已经成为大多数高校论文审核的标配流程。不管你有没有用过A论文,学校都可能会查一遍AI率。很多同学的第一反应就是:ai率查重要多少钱?有没有能免费查AI率的工具? 有免费的aigc检测工具&…...

nli-MiniLM2-L6-H768参数详解:6层768维如何实现速度与精度双优平衡

nli-MiniLM2-L6-H768参数详解:6层768维如何实现速度与精度双优平衡 1. 模型概述 nli-MiniLM2-L6-H768是一个专为自然语言推理(NLI)与零样本分类设计的轻量级交叉编码器(Cross-Encoder)模型。它在保持接近BERT-base精度的同时,通过精巧的架构设计实现了…...

神经网络过拟合与权重衰减实战指南

## 1. 神经网络过拟合的本质与应对策略在训练深度神经网络时,我们常常会遇到一个令人头疼的现象:模型在训练集上表现优异,但在测试集上却一塌糊涂。这就是典型的过拟合问题。过拟合的本质是模型过度记忆了训练数据中的噪声和细节,…...

2026年lpa分层审核系统排行榜:哪款lpa分层审核软件最适合你的工厂?

在2026年的制造业数字化转型浪潮中,lpa分层审核系统(Layered Process Audit System)已成为工厂质量管理的核心工具。随着企业对生产过程稳定性要求的提升,寻找一款最适合你的工厂的lpa分层审核软件变得至关重要。根据最新的行业数…...

从原理到实践:掌握GPT超级提示工程的核心方法与资源

1. 项目概述:当“Awesome”遇见“超级提示”,我们到底在聊什么?如果你最近在AI应用开发或者提示工程(Prompt Engineering)的圈子里混,大概率已经不止一次刷到过“Awesome_GPT_Super_Prompting”这个项目名了…...

Pixel Aurora Engine保姆级教程:从零配置8-BIT扩散模型生成环境

Pixel Aurora Engine保姆级教程:从零配置8-BIT扩散模型生成环境 1. 认识Pixel Aurora引擎 Pixel Aurora是一款专为像素艺术创作设计的AI绘图工作站,它将现代扩散模型技术与复古游戏美学完美结合。与传统AI绘画工具不同,Pixel Aurora采用了独…...

Gemma-4-26B-A4B-it-GGUF惊艳效果:输入Kubernetes Events列表截图→识别频繁事件→关联Pod日志线索

Gemma-4-26B-A4B-it-GGUF惊艳效果:输入Kubernetes Events列表截图→识别频繁事件→关联Pod日志线索 1. 模型能力概览 Gemma-4-26B-A4B-it-GGUF是Google Gemma 4系列中的高性能MoE(混合专家)模型,具备256K tokens的超长上下文处理…...

2026大学生学习数据分析的价值分析

一、数据分析在2026年大学生职业发展中的重要性数据驱动决策成为各行业核心趋势企业对数据分析人才的需求持续增长数据分析技能提升跨行业竞争力二、2026年数据分析领域的核心技能需求编程语言:Python、R、SQL的掌握程度数据可视化工具:Tableau、Power B…...

TensorFlow损失函数实战指南:从原理到工程优化

1. 理解损失函数的核心作用在机器学习的世界里,损失函数就像一位严格的教练,不断告诉模型当前的表现有多糟糕。我在实际项目中见过太多因为选错损失函数导致模型训练失败的案例。TensorFlow作为主流框架,提供了丰富的损失函数实现&#xff0c…...

2015-2025年地级市公共安全基建省内横向压力

数据简介 本数据为探索性研究成果,旨在精准识别视频监控系统建设对地方社会治安治理、居民消费活力、产业结构升级的因果影响,同时为阐释技术治理模式的扩散规律、优化基层治理政策体系提供可靠的实证支撑。 本数据参照梁平汉、郭宇辰和赵玉兰&#xf…...

2.9 会话、窗口站、桌面和窗口消息:图形界面背后的“分层舞台”

🔥个人主页:杨利杰YJlio❄️个人专栏:《Sysinternals实战教程》《Windows PowerShell 实战》《WINDOWS教程》《IOS教程》《微信助手》《锤子助手》 《Python》 《Kali Linux》 《那些年未解决的Windows疑难杂症》🌟 让复杂的事情更…...

导航参数的精细化管理

在React Native应用中,导航是用户体验的一个关键部分,尤其是在处理多屏幕数据传递时,如何管理和区分不同的数据源显得尤为重要。本文将通过一个实际的例子来展示如何通过精细化管理导航参数,解决数据源区分的问题。 问题背景 假设我们有一个应用,包含四个屏幕:Home、Se…...

1985-2025.12最新亿量级裁判文书全量数据

中国裁判文书网是依托最高人民法院政务网站建立的二级网站,栏目包括刑事案件、民事案件、行政案件、赔偿案件、执行案件和知识产权,具备一定的分类和检索功能,另外还设置了专门用于收集社会各界意见的邮箱。网站公布的生效裁判文书&#xff0…...

2.7 受保护进程:那些连 Sysinternals 都“不好惹”的进程

🔥个人主页:杨利杰YJlio❄️个人专栏:《Sysinternals实战教程》《Windows PowerShell 实战》《WINDOWS教程》《IOS教程》《微信助手》《锤子助手》 《Python》 《Kali Linux》 《那些年未解决的Windows疑难杂症》🌟 让复杂的事情更…...

C++之 CMake、CMakeLists.txt、Makefile

这两者的关系其实非常好理解,我们可以用一个**“盖房子”**的例子来打比方。 简单来说:CMake 是“设计师”,Makefile 是“施工图纸”,Make 是“施工队”。 🏠 直白的大白话解释 想象你要盖一栋房子(编译一个…...

财务数字化——解读集团财务管理体系构建【附全文阅读】

适应人群:集团董事长、总裁、CFO / 财务总监、财务经理、子公司经营负责人、战略与人力资源管理者。 重要性总结:本方案是一套国际水准、本土落地的集团化财务管理全案,以价值创造为核心,搭建 “战略 — 组织 — 流程 — 内控 — 资金 — 考核” 一体化闭环体系,直击传统财…...

Python正态性检验全解析:方法对比与实战应用

## 1. 正态性检验的核心价值与应用场景正态分布是统计学中的基石假设,90%的经典统计方法(如t检验、ANOVA、线性回归)都建立在数据服从正态分布的前提上。但在真实数据分析中,我们常遇到这样的困境:一组数据的直方图看起…...

wanwu框架:中文AI应用开发全栈解决方案,从RAG到智能体工作流

1. 项目概述:一个面向中文场景的AI应用开发框架最近在AI应用开发领域,一个名为“wanwu”的项目在开发者社区里引起了不小的讨论。这个由UnicomAI团队开源的项目,定位非常清晰:它旨在为中文场景下的AI应用开发,提供一个…...

LLM应用开发工具全景指南:从RAG到智能体的高效选型与实践

1. 项目概述与核心价值最近在折腾大语言模型(LLM)应用开发时,我遇到了一个非常典型的问题:想法很多,工具很杂。想给模型加个联网搜索功能,发现 LangChain 和 LlamaIndex 都能做,但哪个更适合我的…...

IoC DI 使⽤

既然 Spring 是⼀个IoC(控制反转)容器,作为容器,那么它就具备两个最基础的功能:• 存• 取Spring容器管理的主要是对象,这些对象,我们称之为"Bean".我们把这些对象交由Spring管理,由 Spring来负责对象的创建和销毁.我们…...

AI Agent 面试题 006:Agent的自主性(Autonomy)具体体现在哪些方面?

🔥 AI Agent 面试题 006:Agent的自主性(Autonomy)具体体现在哪些方面?摘要:本文深入解析了「Agent的自主性(Autonomy)具体体现在哪些方面?」这一 AI Agent 领域的核心面试…...

向量检索核心知识整理

一、向量基础:Embedding 与维度选择 1. 向量化核心流程:非结构化数据 → 向量 向量化是将文本、图像、音频等非结构化数据,通过 Embedding 模型 转化为高维稠密向量的过程,是向量检索的基础:数据类型常用模型文本BGE、…...

哈希密钥:解锁unordered容器的极速潜能

目录 一.unordered系列关联式容器 二:unordered_set 1:unordered_set用法详解 1.1:模板参数介绍 1.2:unordered_set的构造函数 1.3:常用接口使用 1.3.1:insert与erase 1.3.2:find与size与empty 1.3.3:clear与swap与count 1.3.4:迭代器 1.3.5:桶操作 三:unordered_ma…...