news 2026/5/11 20:58:23

Springboot数据层开发—Springboot整合JdbcTemplate和Mybatis

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Springboot数据层开发—Springboot整合JdbcTemplate和Mybatis

Springboot整合JdbcTemplate和Mybatis

  • springboot整合JdbcTemplate
  • Springboot整合Mybatis注解方式
  • Springboot整合Mybatis配置文件方式

本文介绍 SpringBoot 整合 JdbcTemplate 和 MyBatis 两种方式,均都体现了SpringBoot简化数据访问层开发的特性。

springboot整合JdbcTemplate

首先需要在数据库中创建表

SETFOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for user-- ----------------------------DROPTABLEIFEXISTS`user`;CREATETABLE`user`(`username`varchar(10)DEFAULTNULL,`userId`int(10)NOTNULL,`password`varchar(10)DEFAULTNULL,PRIMARYKEY(`userId`))ENGINE=InnoDBDEFAULTCHARSET=utf8;

Springboot中提供了JdbcTemplateAutoConfiguration 的自动配置 org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,
JdbcTemplateAutoConfiguration 源码如下:

@ControllerpublicclassTestController{@AutowiredJdbcTemplatejdbcTemplate;@ResponseBody@RequestMapping("/query")publicList<Map<String,Object>>query(){List<Map<String,Object>>maps=jdbcTemplate.queryForList("SELECT * FROM user");returnmaps;}}

由于 Springboot 中提供了 JdbcTemplateAutoConfiguration 的自动配置,直接使用 @Autowired 注解注入即可,启动 springboot,测试访问 http://localhost:8080/query


访问成功

打开监控页面

Springboot整合Mybatis注解方式

导入 mybatis 整合 springboot 模块

<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.1</version></dependency>

com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration

创建JavaBean

importjava.util.Date;publicclassPerson{privateintpid;privateStringpname;privateStringaddr;privateintgender;privateDatebirth;publicPerson(){}publicPerson(intpid,Stringpname,Stringaddr,intgender,Datebirth){this.pid=pid;this.pname=pname;this.addr=addr;this.gender=gender;this.birth=birth;}publicintgetPid(){returnpid;}publicvoidsetPid(intpid){this.pid=pid;}publicStringgetPname(){returnpname;}publicvoidsetPname(Stringpname){this.pname=pname;}publicStringgetAddr(){returnaddr;}publicvoidsetAddr(Stringaddr){this.addr=addr;}publicintgetGender(){returngender;}publicvoidsetGender(intgender){this.gender=gender;}publicDategetBirth(){returnbirth;}publicvoidsetBirth(Datebirth){this.birth=birth;}@OverridepublicStringtoString(){return"Person{"+"pid="+pid+", pname='"+pname+'\''+", addr='"+addr+'\''+", gender="+gender+", birth="+birth+'}';}}

创建Mapper

importjava.util.List;@MapperpublicinterfacePersonMapper{@Select("select * from person")publicList<Person>getPersons();@Select("select * from person t where t.pid = #{id}")publicPersongetPersonById(intid);@Options(useGeneratedKeys=true,keyProperty="pid")@Insert("insert into person(pid, pname, addr,gender, birth)"+" values(#{pid}, #{pname}, #{addr},#{gender}, #{birth})")publicvoidinsert(Personperson);@Delete("delete from person where pid = #{id}")publicvoidupdate(intid);}

其中 @Options(useGeneratedKeys =true, keyProperty = “pid”),MyBatis 会获取到自增的 pid,自动赋值给传入的 person 对象的 pid 属性。

@Mapper 用于明确标记 MyBatis 对应的 Mapper 接口,核心职责是为 MyBatis 提供接口识别信号,触发 MyBatis 对接口的解析与动态代理实现类生成;在 Spring Boot 整合 MyBatis的场景下,该动态代理类会被自动注册为 Spring 容器中的 Bean,支持业务代码通过 @Autowired 直接注入使用。

单元测试

@RunWith(SpringRunner.class)@SpringBootTestpublicclassspringBootMybatisTest{@AutowiredPersonMapperpersonMapper;@TestpublicvoidtestMybatis()throwsSQLException{List<Person>persons=personMapper.getPersons();for(Personperson:persons){System.out.println(person);}}@TestpublicvoidtestMybatis1()throwsSQLException{Personp=personMapper.getPersonById(1);System.out.println(p);}}

开启 MyBatis 的下划线转驼峰命名自动映射功能

@ConfigurationpublicclassMybatisConfig{@BeanpublicConfigurationCustomizergetCustomizer(){returnnewConfigurationCustomizer(){@Overridepublicvoidcustomize(org.apache.ibatis.session.Configurationconfiguration){configuration.setMapUnderscoreToCamelCase(true);}};}}

当项目中 Mapper 接口数量较多,若在每个 Mapper 接口上逐一添加 @Mapper 注解,会增加重复工作量且不易维护。此时可采用 @MapperScan 注解的批量扫描方案。在 MyBatis 相关配置类或 Spring Boot 主启动类上添加 @MapperScan 注解,指定 Mapper 接口所在的包路径,MyBatis 会自动扫描该路径下所有接口,将其识别为 Mapper 接口,无需额外标注 @Mapper,即可完成动态代理实现类的生成与 Spring Bean 的注册。

Springboot整合Mybatis配置文件方式

classpath:mybatis 下创建 sqlMapConfig.xml 全局配置文件

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><settings><settingname="mapUnderscoreToCamelCase"value="true"/></settings></configuration>

其中 mapUnderscoreToCamelCase 值为 true 用于开启下划线转驼峰命名自动映射功能

创建sql映射文件 PersonMapper.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.qcby.springBootMybatis.mapper.PersonMapper"><selectid="getPersons"resultType="com.qcby.springBootMybatis.bean.Person">select * from person</select></mapper>

在 application.yaml 中配置 mybatis 相关配置信息

其中
config-location 值为全局配置文件路径
mapper-locations 值为sql映射文件
type-aliases-package 值为实体类所在包的全路径

测试验证

需要注意的是使用了 Springboot 整合 Mybatis 配置文件方式,Springboot 整合 Mybatis 注解版也同样会生效

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

13、技术文档编写全解析

技术文档编写全解析 在技术领域,文档的编写至关重要,它能帮助用户更好地理解和使用产品。下面将详细介绍技术文档的各个部分、不同类型的技术文档以及编辑在文档编写中的作用。 1. 典型手册各部分的编辑格式 典型手册的各部分通常按照特定顺序排列,以下是各部分的详细介绍…

作者头像 李华
网站建设 2026/5/10 0:32:54

面试常考:如何原地重排数组?这个思路绝了

解题思路 这道题我们用两个指针分别追踪奇数位和偶数位,每次检查最后一个元素是奇数还是偶数,然后把它交换到对应的位置上。 比如最后一个元素是奇数,就把它换到下一个需要填充的奇数位(1, 3, 5…),换过来的元素又成为新的"最后一个元素",继续这个过程。 这样做的优势…

作者头像 李华
网站建设 2026/5/11 15:02:50

Wi-Fi CERTIFIED Multimedia™ (WMM®) 技术概述

1.0 概述 本文档定义了 WMM 的规范,WMM 是基于 IEEE 802.11e 标准补充 [2] 的 802.11 QoS 实现方案。最初提出 WMM 是为了防止因多个不兼容的 802.11e 预标准子集出现而导致的碎片化问题;部署 WMM 将为 802.11 语音、流媒体等服务提供可用的 QoS 功能。 1.1 参考文献 [1] …

作者头像 李华
网站建设 2026/5/11 7:19:51

Astrofy:快速构建现代化个人作品集的免费开源模板

Astrofy&#xff1a;快速构建现代化个人作品集的免费开源模板 【免费下载链接】astrofy Astrofy is a free and open-source template for your Personal Portfolio Website built with Astro and TailwindCSS. Create in minutes a website with Blog, CV, Project Section, S…

作者头像 李华
网站建设 2026/5/11 7:19:48

Opus 音频编解码器深度技术报告:架构原理、传输机制与演进分析

Opus 音频编解码器深度技术报告&#xff1a;架构原理、传输机制与演进分析 1. 引言&#xff1a;音频编码的统一范式 在数字音频处理的历史长河中&#xff0c;音频编码技术长期以来被划分为两个截然不同的阵营&#xff1a;语音编码与通用音频编码。这种二元分化源于应用场景的…

作者头像 李华