Spring整合JDBC
1、引入依赖
<properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><!-- 测试依赖 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><!--核心依赖--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.13.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.13.RELEASE</version></dependency>
<!-- mysql依赖--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency>
<!-- 数据源依赖--><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.2</version></dependency></dependencies><build><plugins>
<!-- 编译插件 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.0</version><configuration><source>1.8</source><target>1.8</target></configuration></plugin></plugins></build>
2、测试连接
连接数据库并且操作的步骤如下 ,连接对应的数据库,前提是本机中存在mysql并且运行以及创建对应的数据库。
然后将四大参数放入,在DriverClass参数中mysql8以上才会由中间的.cj.,8以下没有。url中数据库问号后的内容为字符集的相关设置。
然后通过JdbcTemplate可以对数据库进行相关的操作
@Testpublic void test01( ) throws PropertyVetoException {// 创建数据库ComboPooledDataSource dataSource = new ComboPooledDataSource();dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/springJDBC?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false");dataSource.setUser("root");dataSource.setPassword("123456");// 使用JdbcTemplate template = new JdbcTemplate(dataSource);String sql = "INSERT INTO team (tname , location) VALUES (?, ?)";int update = template.update(sql, "AI2", "郑州2");System.out.println("插入结果: " + update);}
3、spring管理JdbcTemplate
spring整合jdbc可以让dao层继承Spring提供的JdbcDaoSupport类,该类中提供了jdbcTemplate模板可以用来使用。
handlResult函数:是因为在查找的操作中,由重复性的操作,单独拿出来进行封装,用来简化代码。
非查找语句的执行中,都是通过调用JdbcTemplate中的update函数,第一个参数为sql语句,后面跟不定量的参数用来填补sql语句中占位符的位置。
查找语句:
返回数据只有一行的时候使用qyeryForObject函数,第一个位置为sql语句,第二个Object数组内容为参数,用来填补占位符,第三个位置为RowMapper接口用来处理返回的每一行数据,处理结果为需要的数据类型。
返回数据有多行的情况使用query函数,参数类型同上,区别就是query函数的返回值类型为list数组。
返回数据只有一列的情况,第二个参数可以直接用对应类型的类。
返回数据只有一行的情况,并且不是一个类等,可以用Map来存取返回值,使用qyeryForMay,第一个位置为sql语句,第二个Object数组内容为参数,用来填补占位符。
public class TeamDao extends JdbcDaoSupport {public Team handlResult(ResultSet resultSet) throws SQLException {Team team = new Team();team.settId(resultSet.getInt("tid"));team.setLocation(resultSet.getString("location"));team.settName(resultSet.getString("tname"));return team;}public int insert(Team team) {String sql = "insert team (tname, location) values (?, ?)";int update = this.getJdbcTemplate().update(sql, team.gettName(), team.getLocation());return update;}public int update(Team team) {String sql = "update team set tname=?, location=? where tid=?";return this.getJdbcTemplate().update(sql, team.gettName(), team.getLocation(), team.gettId());}public int del(int id) {String sql = "delete from team where tid=?";return this.getJdbcTemplate().update(sql, id);}public Team getTeamById(int id) {String sql = "select * from team where tid=?";Team team = (Team) this.getJdbcTemplate().queryForObject(sql, new Object[] {id}, new RowMapper<Object>() {@Overridepublic Object mapRow(ResultSet resultSet, int i) throws SQLException {return handlResult(resultSet);}});return team;}public List<Team> getTeamAll() {String sql = "select * from team";List<Team> list = this.getJdbcTemplate().query(sql, new RowMapper<Team>() {@Overridepublic Team mapRow(ResultSet resultSet, int i) throws SQLException {return handlResult(resultSet);}});return list;}public int getCount() {String sql = "select count(*) from team";// 如果查询的列只有唯一一列,queryForObject (sql语句,为一列的数据类型)return this.getJdbcTemplate().queryForObject(sql, Integer.class);}public Map<String, Object> getMany() {String sql = "select max(tid) as max, min(tid) as min from team";// 如果查询的列只有唯一一列,queryForObject (sql语句,为一列的数据类型)return this.getJdbcTemplate().queryForMap(sql);}
}
spring的配置文件application.xml中需要创建数据源和给TeamDao中的jdbcTemplate赋值
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
"><!-- 创建数据源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="com.mysql.cj.jdbc.Driver"/><property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/springJDBC?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false"/><property name="user" value="root"/><property name="password" value="123456"/></bean><!-- 创建jdbcTemplate对象,给类中dataSource赋值 --><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"></property></bean><!-- 创建teamDao对象,给类中jdbcTemplate赋值 --><bean id="teamDao" class="com.AE.dao.TeamDao"><property name="jdbcTemplate" ref="jdbcTemplate"/></bean>
</beans>
4、测试
public class test01 {
// private TeamDao teamDao;@Testpublic void test01( ) throws PropertyVetoException {// 创建数据库ComboPooledDataSource dataSource = new ComboPooledDataSource();dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/springJDBC?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false");dataSource.setUser("root");dataSource.setPassword("123456");// 使用JdbcTemplate template = new JdbcTemplate(dataSource);String sql = "INSERT INTO team (tname , location) VALUES (?, ?)";int update = template.update(sql, "AI2", "郑州2");System.out.println("插入结果: " + update);}@Testpublic void test02(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");Team team = new Team();team.setLocation("南阳");team.settName("张淏");int insert = teamDao.insert(team);System.out.println(insert);}@Testpublic void test03(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");Team team = new Team();team.settId(5);team.setLocation("郑州3");team.settName("AI3");int update = teamDao.update(team);System.out.println(update);}@Testpublic void test04(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");int update = teamDao.del(5);System.out.println(update);}@Testpublic void test05(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");Team team = teamDao.getTeamById(2);System.out.println(team);}@Testpublic void test06(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");List<Team> list = teamDao.getTeamAll();for(Team team : list) {System.out.println(team);}System.out.println(list);}@Testpublic void test07(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");int a = teamDao.getCount();System.out.println(a);}@Testpublic void test08(){ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");TeamDao teamDao = (TeamDao) ac.getBean("teamDao");Map<String, Object> many = teamDao.getMany();for(String a : many.keySet()) {System.out.println(a + "=" + many.get(a));}}
}
相关文章:
Spring整合JDBC
1、引入依赖 <properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><depen…...
详解Qt中的布局管理器
Qt中的布局管理是用于组织用户界面中控件(如按钮、文本框、标签等)位置和尺寸调整的一种机制。说白了就是创建了一种规则,随着窗口变化其中的控件大小位置跟着变化。Qt提供了多种布局管理器,每种都有其特定用途和特点。以下是对Qt…...

MyBatis 参数重复打印的bug
现象 最近有个需求,需要在mybatis对数据库进行写入操作的时候,根据条件对对象中的某个值进行置空,然后再进行写入,这样数据库中的值就会为空了。 根据网上查看的资料,选择在 StatementHandler 类执行 update 的时候进…...

ES6学习之路:迭代器Iterator和生成器Generator
迭代器 一、知识背景 什么是迭代器 迭代器就是在一个数据集合中不断取出数据的过程迭代和遍历的区别 遍历是把所有数据都取出迭代器注重的是依次取出数据,它不会在意有多少数据,也不会保证能够取出多少或者能够把数据都取完。比如斐波那契额数列&#…...

如何使用 DynamiCrafter Interp Loop 无缝连接两张照片
DynamiCrafter Interp Loop 是一个基于 AI 的工具,可以用来无缝连接两张照片。它使用深度学习技术来生成中间帧,从而使两张照片之间的过渡更加自然流畅。 使用步骤 访问 DynamiCrafter Interp Loop 网站:https://huggingface.co/spaces/Dou…...

今天起,Windows可以一键召唤GPT-4了
ChatGPT狂飙160天,世界已经不是之前的样子。 新建了人工智能中文站https://ai.weoknow.com 每天给大家更新可用的国内可用chatGPT资源 发布在https://it.weoknow.com 更多资源欢迎关注 微软 AI 大计的最后一块拼图完成了? 把 Copilot 按钮放在 Window…...

使用Kaggle API快速下载Kaggle数据集
前言 在使用Kaggle网站下载数据集时,直接在网页上点击下载可能会很慢,甚至会出现下载失败的情况。本文将介绍如何使用Kaggle API快速下载数据集。 具体步骤 安装Kaggle API包 在终端中输入以下命令来安装Kaggle API相关的包: pip install…...
java 通过 microsoft graph 调用outlook(二)
这次提供一些基础调用方式API PS: getMailFolders 接口返回的属性中,包含了未读邮件数量unreadItemCount 一 POM文件 <!-- office 365 --><dependency><groupId>com.google.guava</groupId><artifactId>guava<…...

【机器学习】代价函数
🎈个人主页:豌豆射手^ 🎉欢迎 👍点赞✍评论⭐收藏 🤗收录专栏:机器学习 🤝希望本文对您有所裨益,如有不足之处,欢迎在评论区提出指正,让我们共同学习、交流进…...

[leetcode] 100. 相同的树
给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。 示例 1: 输入:p [1,2,3], q [1,2,3] 输出:true示例 2&a…...
08、Lua 函数
Lua 函数 Lua 函数Lua函数主要有两种用途函数定义解析:optional_function_scopefunction_nameargument1, argument2, argument3..., argumentnfunction_bodyresult_params_comma_separated 范例 : 定义一个函数 max()Lua 中函数可以作为参数传递给函数多返回值Lua函…...

【数据分析面试】1. 计算年度收入百分比(SQL)
题目 你需要为公司的营收来源生成一份年度报告。计算截止目前为止,在表格中记录的第一年和最后一年所创造的总收入百分比。将百分比四舍五入到两位小数。 示例: 输入: annual_payments 表 列名类型amountINTEGERcreated_atDATETIMEstatusV…...
数据库SQL语句速查手册
SQL 语句语法AND / ORSELECT column_name(s) FROM table_name WHERE condition AND|OR conditionALTER TABLEALTER TABLE table_name ADD column_name datatypeorALTER TABLE table_name DROP COLUMN column_nameAS (alias)SELECT column_name AS column_alias FROM table_name…...

智慧城市一屏统览,数字孪生综合治理
现代城市作为一个复杂系统,牵一发而动全身,城市化进程中产生新的矛盾和社会问题都会影响整个城市系统的正常运转。智慧城市是应对这些问题的策略之一。城市工作要树立系统思维,从构成城市诸多要素、结构、功能等方面入手,系统推进…...

Python读取PDF文字转txt,解决分栏识别问题,能读两栏
搜索了一下,大致有这些库能将PDF转txt 1. PyPDF/PyPDF2(截止2024.03.28这两个已经合并成了一个)pypdf PyPI 2. pdfplumber GitHub - jsvine/pdfplumber: Plumb a PDF for detailed information about each char, rectangle, line, et cete…...

微信支付平台与微信服务号关联配置要点
目录 JSAPI支付 前期资料及相关准备 申请微信服务号 服务号配置要点 微信认证 基本配置 功能设置 申请微信支付号 支付号配置要点 设置操作密码 API安全 开发设置 与服务号关联 小结 JSAPI支付 我们的开发应用场景以JSAPI支付为举例,这也是常用的一…...
C++类复习
C类 1. 类内成员函数隐式声明为inline class Str {int x;int y 3; public:inline void fun(){std::cout<<"pf,yes!"<<std::endl;} };这段代码不会报错,但是类内的成员函数隐式声明为inline函数,不需要单独写在前面。因此将成员…...

Spring使用(一)注解
Spring使用 资源 Spring 框架内部使用 Resource 接口作为所有资源的抽象和访问接口,在上一篇文章的示例代码中的配置文件是通过ClassPathResource 进行封装的,ClassPathResource 是 Resource 的一个特定类型的实现,代表的是位于 classpath …...

Linux基本指令篇
在前边,我们已经了解过了Linux操作系统的发展和应用,从该篇起,就正式进入对Linux的学习。 今天我们就来在Xshell上远程登录我们的云服务器。首先我们要知道自己云服务器的公网ip,然后修改一下密码。 点击跳转 修改完密码之后我们…...

CSS实现小车旅行动画实现
小车旅行动画实现 效果展示 CSS 知识点 灵活使用 background 属性下的 repeating-linear-gradient 实现路面效果灵活运用 animation 属性与 transform 实现小车和其他元素的动画效果 动画场景分析 从效果图可以看出需要实现此动画的话,需要position属性控制元素…...

AI-调查研究-01-正念冥想有用吗?对健康的影响及科学指南
点一下关注吧!!!非常感谢!!持续更新!!! 🚀 AI篇持续更新中!(长期更新) 目前2025年06月05日更新到: AI炼丹日志-28 - Aud…...
SciencePlots——绘制论文中的图片
文章目录 安装一、风格二、1 资源 安装 # 安装最新版 pip install githttps://github.com/garrettj403/SciencePlots.git# 安装稳定版 pip install SciencePlots一、风格 简单好用的深度学习论文绘图专用工具包–Science Plot 二、 1 资源 论文绘图神器来了:一行…...
大模型多显卡多服务器并行计算方法与实践指南
一、分布式训练概述 大规模语言模型的训练通常需要分布式计算技术,以解决单机资源不足的问题。分布式训练主要分为两种模式: 数据并行:将数据分片到不同设备,每个设备拥有完整的模型副本 模型并行:将模型分割到不同设备,每个设备处理部分模型计算 现代大模型训练通常结合…...
CSS设置元素的宽度根据其内容自动调整
width: fit-content 是 CSS 中的一个属性值,用于设置元素的宽度根据其内容自动调整,确保宽度刚好容纳内容而不会超出。 效果对比 默认情况(width: auto): 块级元素(如 <div>)会占满父容器…...

论文笔记——相干体技术在裂缝预测中的应用研究
目录 相关地震知识补充地震数据的认识地震几何属性 相干体算法定义基本原理第一代相干体技术:基于互相关的相干体技术(Correlation)第二代相干体技术:基于相似的相干体技术(Semblance)基于多道相似的相干体…...
MySQL JOIN 表过多的优化思路
当 MySQL 查询涉及大量表 JOIN 时,性能会显著下降。以下是优化思路和简易实现方法: 一、核心优化思路 减少 JOIN 数量 数据冗余:添加必要的冗余字段(如订单表直接存储用户名)合并表:将频繁关联的小表合并成…...
在RK3588上搭建ROS1环境:创建节点与数据可视化实战指南
在RK3588上搭建ROS1环境:创建节点与数据可视化实战指南 背景介绍完整操作步骤1. 创建Docker容器环境2. 验证GUI显示功能3. 安装ROS Noetic4. 配置环境变量5. 创建ROS节点(小球运动模拟)6. 配置RVIZ默认视图7. 创建启动脚本8. 运行可视化系统效果展示与交互技术解析ROS节点通…...
stm32进入Infinite_Loop原因(因为有系统中断函数未自定义实现)
这是系统中断服务程序的默认处理汇编函数,如果我们没有定义实现某个中断函数,那么当stm32产生了该中断时,就会默认跑这里来了,所以我们打开了什么中断,一定要记得实现对应的系统中断函数,否则会进来一直循环…...
Docker、Wsl 打包迁移环境
电脑需要开启wsl2 可以使用wsl -v 查看当前的版本 wsl -v WSL 版本: 2.2.4.0 内核版本: 5.15.153.1-2 WSLg 版本: 1.0.61 MSRDC 版本: 1.2.5326 Direct3D 版本: 1.611.1-81528511 DXCore 版本: 10.0.2609…...

Element-Plus:popconfirm与tooltip一起使用不生效?
你们好,我是金金金。 场景 我正在使用Element-plus组件库当中的el-popconfirm和el-tooltip,产品要求是两个需要结合一起使用,也就是鼠标悬浮上去有提示文字,并且点击之后需要出现气泡确认框 代码 <el-popconfirm title"是…...