新闻详情

新闻详情

首页 / 资讯中心 / 详情

Spring:MyBatis操作数据库 1

发布时间:2026/9/29 7:02:28来源:尧图网络
Spring:MyBatis操作数据库 1
1.什么是MyBatis?•MyBatis是⼀款优秀的 持久层 框架⽤于简化JDBC的开发。•MyBatis本是 Apache的⼀个开源项⽬iBatis2010年这个项⽬由apache迁移到了google code并且改名为MyBatis 。2013年11⽉迁移到Github.•官⽹MyBatis中⽂⽹在上⾯我们提到⼀个词持久层•持久层指的就是持久化操作的层, 通常指数据访问层(dao), 是⽤来操作数据库的.简单来说 MyBatis 是更简单完成程序和数据库交互的框架也就是更简单的操作和读取数据库⼯具接下来我们就通过⼀个⼊⻔程序让⼤家感受⼀下通过Mybatis如何来操作数据库2.MyBatis⼊⻔2.1准备⼯作创建springboot⼯程并导⼊ mybatis的起步依赖、mysql的驱动包Mybatis 是⼀个持久层框架, 具体的数据存储和数据操作还是在MySQL中操作的, 所以需要添加MySQL驱动项⽬⼯程创建完成后⾃动在pom.xml⽂件中导⼊Mybatis依赖和MySQL驱动依赖版本会随着SpringBoot 版本发⽣变化SpringBoot 3.X对⽤MyBatis版本为3.X对应关系参考:https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/1!--Mybatis依赖包--2dependency3groupIdorg.mybatis.spring.boot/groupId4artifactIdmybatis-spring-boot-starter/artifactId5version3.0.3/version6/dependency7!--mysql驱动包--8dependency9groupIdcom.mysql/groupId10artifactIdmysql-connector-j/artifactId11scoperuntime/scope12/dependency2.2配置数据库连接字符串Mybatis中要连接数据库需要数据库相关参数配置•MySQL驱动类•登录名•密码•数据库连接字符串如果是application.yml⽂件, 配置内容如下:#数据库连接配置spring:datasource:url:jdbc:mysql://127.0.0.1:3306/mybatis_test? characterEncodingutf8useSSLfalseusername:rootpassword:rootdriver-class-name:com.mysql.cj.jdbc.Driver注意事项如果使⽤ MySQL 是 5.x 之前的使⽤的是com.mysql.jdbc.Driver如果是⼤于 5.x 使⽤的是“com.mysql.cj.jdbc.Driver”.如果是application.properties⽂件, 配置内容如下:#驱动类名称spring.datasource.driver-class-namecom.mysql.cj.jdbc.Driver#数据库连接的urlspring.datasource.urljdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncodingutf8useSSLfalse#连接数据库的⽤⼾名spring.datasource.usernameroot#连接数据库的密码spring.datasource.passwordroot2.3写持久层代码在项⽬中, 创建持久层接⼝UserInfoMapperimportcom.example.demo.model.UserInfo;importorg.apache.ibatis.annotations.Mapper;importorg.apache.ibatis.annotations.Select;importjava.util.List;Mapperpublic interfaceUserInfoMapper{//查询所有⽤⼾Select(select username, password, age, gender, phone from user_info)publicListUserInfoqueryAllUser();}Mybatis的持久层接⼝规范⼀般都叫 XxxMapperMapper注解表⽰是MyBatis中的Mapper接⼝•程序运⾏时, 框架会⾃动⽣成接⼝的实现类对象(代理对象)并给交Spring的IOC容器管理•Select注解代表的就是select查询也就是注解对应⽅法的具体实现内容.2.4单元测试在创建出来的SpringBoot⼯程中在src下的test⽬录下已经⾃动帮我们创建好了测试类 我们可以直接使⽤这个测试类来进⾏测试.1importcom.example.demo.mapper.UserInfoMapper;2importcom.example.demo.model.UserInfo;3importorg.junit.jupiter.api.Test;4importorg.springframework.beans.factory.annotation.Autowired;5importorg.springframework.boot.test.context.SpringBootTest;67importjava.util.List;89SpringBootTest10classDemoApplicationTests{1112Autowired13privateUserInfoMapper userInfoMapper;1415Test16voidcontextLoads() {17ListUserInfo userInfoList userInfoMapper.queryAllUser();18System.out.println(userInfoList);19}20}测试类上添加了注解 SpringBootTest该测试类在运⾏时就会⾃动加载Spring的运⾏环境.我们通过Autowired这个注解, 注⼊我们要测试的类, 就可以开始进⾏测试了3.MyBatis的基础操作3.1打印⽇志在Mybatis当中我们可以借助⽇志, 查看到sql语句的执⾏、执⾏传递的参数以及执⾏结果在配置⽂件中进⾏配置即可1mybatis:2configuration:#配置打印MyBatis⽇志3log-impl:org.apache.ibatis.logging.stdout.StdOutImpl如果是application.properties, 配置内容如下:1#指定mybatis输出⽇志的位置,输出控制台2mybatis.configuration.log-implorg.apache.ibatis.logging.stdout.StdOutImpl重新运⾏程序, 可以看到SQL执⾏内容, 以及传递参数和执⾏结果3.2参数传递需求: 查找id4的⽤⼾,对应的SQL就是: select * from user_info where id41Select(select username, password, age, gender, phone from user_info where id 4 )2UserInfoqueryById();但是这样的话, 只能查找id4的数据, 所以SQL语句中的id值不能写成固定数值需要变为动态的值解决⽅案在queryById⽅法中添加⼀个参数(id)将⽅法中的参数传给SQL语句使⽤ #{}的⽅式获取⽅法中的参数1Select(select username, password, age, gender, phone from user_info where id #{id} )2UserInfoqueryById(Integer id);如果mapper接⼝⽅法形参只有⼀个普通类型的参数#{…} ⾥⾯的属性名可以随便写如#{id}、#{value}。建议和参数名保持⼀致也可以通过Param, 设置参数的别名, 如果使⽤Param设置别名, #{...}⾥⾯的属性名必须和Param设置的⼀样1Select(select username, password, age, gender, phone from user_info where id #{userid} )2UserInfoqueryById(Param(userid)Integer id);3.3增(Insert)SQL 语句:1Insert(insert into user_info (username, password, age, gender, phone) values (#{username},#{password},#{age},#{gender},#{phone}))2Integerinsert(UserInfo userInfo);返回主键Insert 语句默认返回的是受影响的⾏数但有些情况下, 数据插⼊之后, 还需要有后续的关联操作, 需要获取到新插⼊数据的id⽐如订单系统,当我们下完订单之后, 需要通知物流系统, 库存系统, 结算系统等, 这时候就需要拿到订单ID如果想要拿到⾃增id, 需要在Mapper接⼝的⽅法上添加⼀个Options的注解Options(useGeneratedKeys true, keyProperty id)Insert(insert into user_info (username, age, gender, phone) values (#{userInfo.username},#{userInfo.age},#{userInfo.gender},#{userInfo.phone}))Integerinsert(Param(userInfo)UserInfo userInfo);•useGeneratedKeys这会令 MyBatis 使⽤ JDBC 的 getGeneratedKeys ⽅法来取出由数据库内部⽣成的主键⽐如像 MySQL 和 SQL Server 这样的关系型数据库管理系统的⾃动递增字段默认值false.•keyProperty指定能够唯⼀识别对象的属性MyBatis 会使⽤ getGeneratedKeys 的返回值或insert 语句的 selectKey ⼦元素设置它的值默认值未设置unset3.4删(Delete)SQL 语句:1Delete(delete from user_info where id #{id})2voiddelete(Integer id);3.5改(Update)SQL 语句:1Update(update user_info set username#{username} where id#{id})2voidupdate(UserInfo userInfo);3.6查(Select)我们在上⾯查询时发现, 有⼏个字段是没有赋值的, 只有Java对象属性和数据库字段⼀模⼀样时, 才会进⾏赋值,接下来我们多查询⼀些数据1Select(select id, username, password, age, gender, phone, delete_flag,create_time, update_time from user_info)2ListUserInfoqueryAllUser();当⾃动映射查询结果时MyBatis 会获取结果中返回的列名并在 Java 类中查找相同名字的属性忽略⼤⼩写。 这意味着如果发现了 ID 列和 id 属性MyBatis 会将列 ID 的值赋给 id 属性3.6.1起别名在SQL语句中给列名起别名保持别名和实体类属性名⼀样Select(select id, username, password, age, gender, phone, delete_flag as deleteFlag, create_time as createTime, update_time as updateTime from user_info)publicListUserInfoqueryAllUser();SQL语句太⻓时, 使⽤加号进⾏字符串拼接3.6.2结果映射1Select(select id, username, password, age, gender, phone, delete_flag,create_time, update_time from user_info)2Results({3Result(column delete_flag,property deleteFlag),4Result(column create_time,property createTime),5Result(column update_time,property updateTime)6})7ListUserInfoqueryAllUser();如果其他SQL, 也希望可以复⽤这个映射关系, 可以给这个Results定义⼀个名称1Select(select id, username, password, age, gender, phone, delete_flag,create_time, update_time from user_info)2Results(id resultMap,value {3Result(column delete_flag,property deleteFlag),4Result(column create_time,property createTime),5Result(column update_time,property updateTime)6})7ListUserInfoqueryAllUser();89Select(select id, username, password, age, gender, phone, delete_flag, create_time, update_time from user_info where id #{userid} )10ResultMap(value resultMap)11UserInfoqueryById(Param(userid)Integer id);使⽤id属性给该Results定义别名, 使⽤ResultMap注解来复⽤其他定义的ResultMap3.6.3开启驼峰命名(推荐)通常数据库列使⽤蛇形命名法进⾏命名(下划线分割各个单词), ⽽ Java 属性⼀般遵循驼峰命名法约定. 为了在这两种命名⽅式之间启⽤⾃动映射需要将 mapUnderscoreToCamelCase设置为 true。1mybatis:configuration:map-underscore-to-camel-case:true#配置驼峰⾃动转换驼峰命名规则 abc_xyz abcXyz•表中字段名abc_xyz•类中属性名abcXyzJava 代码不做任何处理Select(select id, username, password, age, gender, phone, delete_flag, create_time, update_time from user_info)publicListUserInfoqueryAllUser();
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

HandyControl ContextMenuButton 上下文菜单按钮:用法、源码解析与实战示例 2026/9/29 7:53:42

HandyControl ContextMenuButton 上下文菜单按钮:用法、源码解析与实战示例

UI组件桌面应用 【免费下载链接】HandyControl Contains some simple and commonly used WPF controls 项目地址: https://gitcode.com/gh_mirrors/ha/HandyControl 点击查看 免费下载 导读 ContextMenuButton 与 ContextMenuToggleButton 是 HandyControl&#x…

阅读更多 →
华为OD机试真题精讲:停车场车辆统计(Python/Java/C++多语言实现) 2026/9/29 7:53:42

华为OD机试真题精讲:停车场车辆统计(Python/Java/C++多语言实现)

华为OD机试真题精讲:停车场车辆统计(Python/Java/C++多语言实现) 一、题目描述(2025B卷高频100分题) 停车场需要统计特定时间段内的车辆停留情况,需根据以下规则计算指定时间点停车场内的车辆总数: 输入为: 车辆进出记录列表records,每个元素为[license_plate, in_t…

阅读更多 →
GPU利用率低?PyTorch数据加载与预处理优化实战 2026/9/29 7:53:29

GPU利用率低?PyTorch数据加载与预处理优化实战

GPU利用率卡在40%上下,显卡风扇转得跟没转一样,训练一个batch要等半天——跑PyTorch训练的都会遇到这种“显卡罢工”的场面。多数人第一反应是加num_workers,结果往往只是从40%挪到55%,问题依旧。我这些年处理过不少这类性能排查&…

阅读更多 →
TensorFlow实战指南:从环境配置到模型部署的完整链路 2026/9/29 7:53:29

TensorFlow实战指南:从环境配置到模型部署的完整链路

打开TensorFlow官方文档的那一刻,我相信很多人和我一样——本来只是想快速跑通一个模型,结果面对版本号、CUDA、GPU驱动、环境变量这一堆名词,整整折腾了一个下午。2024年的深度学习框架圈子里,"TensorFlow是不是已经被PyTor…

阅读更多 →
银河麒麟高级服务器操作系统V10SP3-2403部署 Kubernetes 1.33.7+containerd + Calico 完整实战 2026/9/29 7:53:29

银河麒麟高级服务器操作系统V10SP3-2403部署 Kubernetes 1.33.7+containerd + Calico 完整实战

环境说明:本文基于银河麒麟高级服务器操作系统 V10 SP3 2403(x86_64)搭建 Kubernetes 集群,部署规模为 1 master 1 node。 组件版本: Kubernetes:v1.33.7containerd:containerd.io 1.6.33CNI&a…

阅读更多 →
NG-ZORRO Tabs 标签页组件实战指南:完整 API 解析与源码级原理剖析 2026/9/29 7:53:22

NG-ZORRO Tabs 标签页组件实战指南:完整 API 解析与源码级原理剖析

UI组件前端 【免费下载链接】ng-zorro-antd Angular UI Component Library based on Ant Design 项目地址: https://gitcode.com/gh_mirrors/ng/ng-zorro-antd 点击查看 免费下载 标签页(Tabs)是 NG-ZORRO 中最常用的导航类组件之一&#xf…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞 ✉