news 2026/9/4 21:06:15

《SpringBoot 3:入门与应用实战》第 12 章 JDBC 与事务 使用 JdbcTemplate 阅读笔记 32

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
《SpringBoot 3:入门与应用实战》第 12 章 JDBC 与事务 使用 JdbcTemplate 阅读笔记 32

《SpringBoot 3:入门与应用实战》第 12 章 JDBC 与事务 使用 JdbcTemplate 阅读笔记 32

12.2.2 JdbcTemplate 应用于 Dao 层

虽然已经可以使用 JdbcTemplate 完成对数据的 CRUD 操作,但是目前的代码中有一个非常大的问题:与数据库操作相关的 API 应当集中到 Dao层的 API 中,而不是直接注入 Controller 层。所以下面要做的是将 JdbcTemplate 的使用移入 Dao 层。

模拟一个贴近真实开发环境的代码结构,新建一个 dao 包,并在其中创建一个接口 UserDao,声明 3 个方法。注意,这次只演示了保存操作和查列表、查单条数据的操作,并未涉及全部内容。

publicinterfaceUserDao{voidsave(Useruser);UserfindById(Integerid);List<User>findAll();}

紧接着是 UserDao 的实现类 UserDaoImpl,注意这个实现类上需要使用 @Repository 标注,该注解同样是 @Component 的派生注解,可以被Spring Boot 扫描到并注入进 IOC 容器。

packagecom.yangjunbo.springboot.jdbc.exampleb;importcom.yangjunbo.springboot.jdbc.examplea.User;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.jdbc.core.BeanPropertyRowMapper;importorg.springframework.jdbc.core.JdbcTemplate;importorg.springframework.stereotype.Repository;importjava.util.List;@RepositorypublicclassUserDaoImplimplementsUserDao{@AutowiredprivateJdbcTemplatejdbcTemplate;@Overridepublicvoidsave(Useruser){jdbcTemplate.update("insert into tbl_user (name, tel) values (?, ?)",user.getName(),user.getTel());}@OverridepublicUserfindById(Integerid){List<User>userList=jdbcTemplate.query("select * from tbl_user where id = ?",newBeanPropertyRowMapper<>(User.class),id);returnuserList.size()>0?userList.get(0):null;}@OverridepublicList<User>findAll(){returnjdbcTemplate.query("select * from tbl_user",newBeanPropertyRowMapper<>(User.class));}}

最后在需要操作 tbl_user 表的位置注入 UserDao 即可,不需要再注入 JdbcTemplate 组件。

12.2.3 查询策略

1.queryForList

顾名思义,queryForList 方法的返回值一定是一个 List,借助 IDE 可以发现 JdbcTemplate 中有 7 个重载的 queryForList 方法,这些方法会根据是否传入 elementType 决定返回指定的类型还是 Map,注意 “指定的类型” 这个概念,只有当查询结果只有单列时才可以指定,否则会出现列数过多的异常。

在讲解 select 系列方法中已经介绍过指定类型的方法,代码展示了一个返回 Map<String, Object> 的查询示例,这种查询的方式通常在临时查询一批数据时使用。重新编译代码后访问 /test11 接口,浏览器中得到了数据,与预期相同。

packagecom.yangjunbo.springboot.jdbc.examplea;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.jdbc.core.BeanPropertyRowMapper;importorg.springframework.jdbc.core.JdbcTemplate;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RestController;importjava.util.List;importjava.util.Map;@RestControllerpublicclassJdbcTemplateController{@AutowiredprivateJdbcTemplatejdbcTemplate;@GetMapping("/test1")publicStringtest1(){System.out.println(jdbcTemplate);return"success";}@GetMapping("/test2")publicStringtest2(){Useruser=newUser();user.setName("heihei");user.setTel("200");introw=jdbcTemplate.update("insert into tbl_user (name, tel) values (?, ?)",user.getName(),user.getTel());return"success - "+row;}@GetMapping("/test3")publicStringtest3(){Useruser=newUser();user.setName("heihei");user.setTel("54321");introw=jdbcTemplate.update("update tbl_user set tel = ? where name = ?",user.getTel(),user.getName());return"success - "+row;}@GetMapping("/test4")publicStringtest4(){introw=jdbcTemplate.update("delete from tbl_user where name = ?","heihei");return"success - "+row;}@GetMapping("/test5")publicList<User>test5(){List<User>userList=jdbcTemplate.query("select * from tbl_user",newBeanPropertyRowMapper<>(User.class));returnuserList;}@GetMapping("/test6")publicList<User>test6(){List<User>userList=jdbcTemplate.query("select * from tbl_user where id > ?",newBeanPropertyRowMapper<>(User.class),2);returnuserList;}@GetMapping("/test7")publicUsertest7(intid){Useruser=jdbcTemplate.queryForObject("select * from tbl_user where id = ?",newBeanPropertyRowMapper<>(User.class),id);returnuser;}@GetMapping("/test8")publicUsertest8(intid){List<User>userList=jdbcTemplate.query("select * from tbl_user where id = ?",newBeanPropertyRowMapper<>(User.class),id);Useruser=userList.size()>0?userList.get(0):null;returnuser;}@GetMapping("/test9")publicUsertest9(intid){Useruser=jdbcTemplate.queryForObject("select * from tbl_user where id = ?",User.class,id);returnuser;}@GetMapping("/test10")publicIntegertest10(){Integercount=jdbcTemplate.queryForObject("select count(*) from tbl_user",Integer.class);returncount;}@GetMapping("/test11")publicList<Map<String,Object>>test11(){List<Map<String,Object>>userList=jdbcTemplate.queryForList("select * from tbl_user where id > 3");returnuserList;}}

返回 Map<String, Object> 结构的 queryForList 方法通常在项目开发中使用不多,但以笔者的工作经历来看,这个方法很适合用来临时查询一批数据,并对这些数据进行操作,由于 JdbcTemplate 只需要依赖数据源,因此使用 JdbcTemplate 处理临时的一次性工作非常顺手。

2.queryForMap

queryForMap 方法也是一个非常好理解的方法,这个系列的方法都会返回 Map<String,Object>。注意,这个方法只会返回一条数据,所以这个方法适用于查询单条数据的场景。代码提供了一个非常简单的 queryForMap 方法的使用。

有关 JdbcTemplate 的常用方式就介绍这些,在实际项目开发中 JdbcTemplate 使用频率不高,但就其本身而言,JdbcTemplate 不失为一个简单实用的 JDBC API,读者可以在恰当的场景中合理利用。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/4 21:06:01

跨平台微信数据库解密与实时监听工具:内存取证与SQLCipher实战

简介&#xff1a;这是一套面向安全研究人员、逆向工程师及自动化办公开发者的技术工具集&#xff0c;聚焦微信4.0跨平台&#xff08;Windows/macOS/Linux&#xff09;本地数据库解密与实时消息监听场景&#xff0c;解决多群消息过载、关键信息易遗漏、加密数据无法复用等实际痛…

作者头像 李华
网站建设 2026/9/4 21:04:51

福州弘善优才联系电话|福州央国企线上一站式求职服务咨询方式

一、福州弘善优才是做什么的&#xff1f;不少准备报考福建地区央国企的求职者&#xff0c;常会咨询福州弘善优才联系方式、福州弘善优才咨询电话&#xff0c;希望对接专业、正规的求职辅导资源。福州弘善优才是专注于央国企求职赛道的服务品牌&#xff0c;主打线上一站式求职服…

作者头像 李华
网站建设 2026/9/4 21:04:22

C++本地文件共享工具:HTML界面+内存映射实战

简介&#xff1a;这是一套面向C网络编程学习者与Qt跨平台开发者的共享云盘项目源码&#xff0c;聚焦于本地化云存储服务的设计与实现&#xff0c;适用于课程设计、毕设开发及中小型分布式存储系统原型验证。资源共40个文件&#xff0c;压缩包大小5.89MB&#xff0c;涵盖9个C头文…

作者头像 李华
网站建设 2026/9/4 21:03:07

问数Agent赋能先进制造设备分析:一线自主查询异常数据

导语 在高端装备、新能源制造、汽车零部件等先进制造领域&#xff0c;设备运行异常是影响生产效率、产品质量的常见问题。传统模式下&#xff0c;一线设备经理、维护工程师发现设备数据异常后&#xff0c;需要提交取数需求给数据部门或IT团队&#xff0c;等待若干工作日才能拿…

作者头像 李华
网站建设 2026/9/4 21:02:38

巴渝文化美食网站:纯前端CSS语义化设计实践

简介&#xff1a;本资源是一套面向前端开发初学者与文化类网站实践者的巴渝美食文化主题网站源码&#xff0c;聚焦地域文化传播场景&#xff0c;解决地方特色内容数字化展示与交互体验构建问题。压缩包共65个文件&#xff0c;含5个HTML页面构成网站骨架&#xff0c;10个CSS文件…

作者头像 李华
网站建设 2026/9/4 21:00:46

航拍小目标检测实战:从YOLOv8优化到工程部署全链路解析

简介&#xff1a;本资源是一套面向计算机视觉初学者与算法工程师的小目标检测实战项目&#xff0c;聚焦航拍图像中尺寸小、分辨率低目标的精准识别难题&#xff0c;适用于安防监控、遥感分析、无人机巡检等实际场景。项目基于YOLOv8框架&#xff0c;针对性改进网络结构、损失函…

作者头像 李华