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

Spring零基础 JdbcTemplate 数据库操作 :两种DAO写法

在 Spring 框架中,JdbcTemplate是 Spring 自带的数据库操作工具,简化了原生JDBC的繁琐代码,不需要手动获取连接、关闭连接。本文讲解两种DAO编写方式,使用模拟转账案例,通俗易懂,适合新手学习。

一、环境准备

Maven 依赖(pom.xml)

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.qcby</groupId> <artifactId>spring-aop-demo</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- Spring核心 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.31</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.31</version> </dependency> <!-- 注解支持 --> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency> <!-- 日志 --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <!-- 测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.3.31</version> <scope>test</scope> </dependency> <!-- 数据库 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency> <!-- AOP 相关 --> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.3.31</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.3</version> </dependency> </dependencies> </project>

配置文件:application.properties存放数据库连接信息

jdbc.driverClassName=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql:///spring_db?useSSL=false&serverTimezone=UTC jdbc.username=root jdbc.password=123456

二、数据库表结构

CREATE TABLE account( name VARCHAR(20), money DOUBLE ); -- 初始化数据 INSERT INTO account VALUES ('熊大',1000),('熊二',500);

✨三、 方式一:普通 DAO(手动注入 JdbcTemplate)

1、项目结构

com.qcby.demo2 ├─AccountService 业务接口 ├─AccountServiceImpl 业务实现 ├─AccountDao 数据层接口 └─AccountDaoImpl 数据层实现

2、Service 层代码

public interface AccountService { void pay(String out,String in,double money); }
public class AccountServiceImpl implements AccountService { private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Override public void pay(String out, String in, double money) { // 转账:扣款+加款 accountDao.outMoney(out,money); accountDao.inMoney(in,money); } }

3、Dao 层代码

public interface AccountDao { void outMoney(String out,double money); void inMoney(String in,double money); }
public class AccountDaoImpl implements AccountDao { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public void outMoney(String out, double money) { jdbcTemplate.update("update account set money=money-? where name=?",money,out); } @Override public void inMoney(String in, double money) { jdbcTemplate.update("update account set money=money+? where name=?",money,in); } }

4、XML 配置文件

<context:property-placeholder location="classpath:application.properties"/> <!-- 连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- Jdbc模板 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="accountDao" class="com.qcby.demo2.AccountDaoImpl"> <property name="jdbcTemplate" ref="jdbcTemplate"/> </bean> <bean id="accountService" class="com.qcby.demo2.AccountServiceImpl"> <property name="accountDao" ref="accountDao"/> </bean>

✨四、 方式二:继承 JdbcDaoSupport(简化 DAO 写法)

1、特点

不用手动注入 JdbcTemplate,DAO 类继承JdbcDaoSupport,只需要注入数据源,内部自动封装 JdbcTemplate。

2、Dao 实现类

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao { @Override public void outMoney(String out, double money) { getJdbcTemplate().update("update account set money = money - ? where name = ?",money,out); } @Override public void inMoney(String in, double money) { getJdbcTemplate().update("update account set money = money + ? where name = ?",money,in); } }

3、XML 配置

<?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/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 location="classpath:application.properties"/> <!-- 连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 【第二种Dao写法】注入 dataSource 即可,不需要JdbcTemplate --> <bean id="accountDao" class="com.qcby.demo3.AccountDaoImpl"> <property name="dataSource" ref="dataSource"/> </bean> <!-- Service --> <bean id="accountService" class="com.qcby.demo3.AccountServiceImpl"> <property name="accountDao" ref="accountDao"/> </bean> </beans>

五、测试代码

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext_dao2.xml") public class Demo3Test { @Autowired private AccountService accountService; @Test public void testPay() { accountService.pay("熊大", "熊二", 100); System.out.println("✅ 转账成功"); } }

六、两种 DAO 方式

方式特点
普通 DAO手动注入 JdbcTemplate,灵活
继承 JdbcDaoSupport代码简洁,不用声明模板
http://www.jsqmd.com/news/773635/

相关文章:

  • VS Code Cursor主题深度解析:从柔和色系设计到高效编码环境配置
  • 基于混合储能的新能源汽车能量管理策略电动公交车【附代码】
  • 创业团队如何利用 Taotoken 统一管理多个 AI 模型的 API 密钥
  • AutoSar NVM数据同步的‘潜规则’:从一次RAM数据踩坑说起,聊聊回调与轮询的正确姿势
  • 营销黑客的着陆页生成器:用代码化与自动化驱动高效转化
  • AI洗牌UI行业:低端画图工被淘汰,真正懂行的设计师越混越值钱
  • 流浪动物救助微信小程序(30251)
  • 导航功能开发博客 3:实时状态、偏航判断与兜底机制
  • AISMM评估为何反复被退回?:揭秘SITS2026评审组内部打分逻辑与3个未公开否决红线
  • Java 学习打卡 Day6:方法基础入门
  • macOS外接显示器亮度调节终极指南:如何用MonitorControl告别物理按钮烦恼
  • 开源风险发现工具Riskow:上下文感知的云原生安全风险评估实践
  • 对比使用聚合平台前后在模型选型与切换上的效率提升
  • douyin-downloader:面向未来的智能内容管理架构
  • ESP32-H2开发板硬件优化与多协议开发实战
  • singleflight
  • AI模型平台选型革命:国产新秀模力方舟如何打破大厂垄断格局
  • 汽车CAN总线实时系统设计与响应时间分析
  • 终极指南:5分钟快速上手Open-Lyrics,让AI为你的音频自动生成精准字幕
  • 洛谷P1074 [NOIP 2009 提高组] 靶形数独题解
  • Fernflower:Java字节码智能反编译的艺术与实践
  • 如何用FUnIE-GAN打破水下视觉迷雾?3分钟掌握实时图像增强核心技术
  • 零基础如何做车载嵌入式开发?学好C++至关重要
  • 【DAY 1.数据结构之反转链表1.牛客网BM1】
  • 多智能体协作框架:AI驱动的软件开发团队自动化实践
  • OpenCore Legacy Patcher:突破苹果硬件限制的系统兼容性架构解析
  • Gemini3.1Pro一键生成高效教研方案
  • 氢燃料微型燃气轮机增程系统建模及控制策略【附代码】
  • 开源中国的国产化突围:构建安全可控的智能研发生态体系
  • 分布式搜索引擎:Elasticsearch 从入门到实战