news 2026/5/8 1:14:53

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
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代码简洁,不用声明模板
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/8 1:14:29

为AI Agent集成Tavily API:构建实时信息检索技能的设计与实现

1. 项目概述&#xff1a;为AI Agent注入实时信息检索能力在构建和部署AI智能体&#xff08;Agent&#xff09;时&#xff0c;一个核心的挑战是如何让它们摆脱静态知识的束缚&#xff0c;获取实时、准确的外部信息。无论是进行市场调研、监控竞争对手动态&#xff0c;还是追踪行…

作者头像 李华
网站建设 2026/5/8 1:06:28

AI数据流编排框架AirWeave:构建高效实时数据处理管道

1. 项目概述&#xff1a;当AI遇上数据编织最近在开源社区里&#xff0c;一个名为airweave-ai/airweave的项目引起了我的注意。这个名字本身就很有意思&#xff0c;“Air”让人联想到轻量、无处不在&#xff0c;“Weave”则是编织、交织的意思。简单来说&#xff0c;这是一个旨在…

作者头像 李华
网站建设 2026/5/8 1:03:17

利用MCP协议与mcp-conf工具,为AI编程助手构建深度项目感知能力

1. 项目概述&#xff1a;一个为AI编码助手配置MCP服务器的工具 如果你和我一样&#xff0c;日常重度依赖 Cursor 或者 Cline 这类 AI 编程助手&#xff0c;那你肯定对它们强大的代码生成和问题解答能力印象深刻。但有时候&#xff0c;你可能会觉得助手对项目内部特定文件、数据…

作者头像 李华
网站建设 2026/5/8 0:59:23

六层板可靠性检验别省步骤!

六层板可靠性检验常被 “简化”&#xff1a;为赶交期、降成本&#xff0c;省略热循环、湿热、振动、盐雾测试&#xff0c;只做基础检验&#xff0c;结果设备投入使用后&#xff0c;短期就出现故障&#xff1a;高温开裂、潮湿漏电、振动脱落、腐蚀断路&#xff0c;寿命从 5 年缩…

作者头像 李华