Mybatis3 调用存储过程

1. 数据库MySQL,user表

CREATE TABLE `user` (`USER_ID` int NOT NULL AUTO_INCREMENT,`USER_NAME` varchar(100) NOT NULL COMMENT '用户姓名',`AGE` int NOT NULL COMMENT '年龄',`CREATED_TIME` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,`CREATED_BY` varchar(100) NOT NULL DEFAULT 'UNKNOWN',`UPDATED_TIME` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,`UPDATED_BY` varchar(100) NOT NULL DEFAULT 'UNKNOWN',PRIMARY KEY (`USER_ID`)) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb3

 

2.使用Mybatis-generator生成POJO等对象

具体使用方法参考文章:Mybatis Generator 使用手册-CSDN博客

User.java

package com.derek.model;import java.util.Date;public class User {/**** This field was generated by MyBatis Generator.* This field corresponds to the database column user.USER_ID** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/private Integer userId;/**** This field was generated by MyBatis Generator.* This field corresponds to the database column user.USER_NAME** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/private String userName;/**** This field was generated by MyBatis Generator.* This field corresponds to the database column user.AGE** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/private Integer age;/**** This field was generated by MyBatis Generator.* This field corresponds to the database column user.CREATED_TIME** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/private Date createdTime;/**** This field was generated by MyBatis Generator.* This field corresponds to the database column user.CREATED_BY** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/private String createdBy;/**** This field was generated by MyBatis Generator.* This field corresponds to the database column user.UPDATED_TIME** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/private Date updatedTime;/**** This field was generated by MyBatis Generator.* This field corresponds to the database column user.UPDATED_BY** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/private String updatedBy;/*** This method was generated by MyBatis Generator.* This method returns the value of the database column user.USER_ID** @return the value of user.USER_ID** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public Integer getUserId() {return userId;}/*** This method was generated by MyBatis Generator.* This method sets the value of the database column user.USER_ID** @param userId the value for user.USER_ID** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public void setUserId(Integer userId) {this.userId = userId;}/*** This method was generated by MyBatis Generator.* This method returns the value of the database column user.USER_NAME** @return the value of user.USER_NAME** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public String getUserName() {return userName;}/*** This method was generated by MyBatis Generator.* This method sets the value of the database column user.USER_NAME** @param userName the value for user.USER_NAME** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public void setUserName(String userName) {this.userName = userName;}/*** This method was generated by MyBatis Generator.* This method returns the value of the database column user.AGE** @return the value of user.AGE** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public Integer getAge() {return age;}/*** This method was generated by MyBatis Generator.* This method sets the value of the database column user.AGE** @param age the value for user.AGE** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public void setAge(Integer age) {this.age = age;}/*** This method was generated by MyBatis Generator.* This method returns the value of the database column user.CREATED_TIME** @return the value of user.CREATED_TIME** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public Date getCreatedTime() {return createdTime;}/*** This method was generated by MyBatis Generator.* This method sets the value of the database column user.CREATED_TIME** @param createdTime the value for user.CREATED_TIME** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public void setCreatedTime(Date createdTime) {this.createdTime = createdTime;}/*** This method was generated by MyBatis Generator.* This method returns the value of the database column user.CREATED_BY** @return the value of user.CREATED_BY** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public String getCreatedBy() {return createdBy;}/*** This method was generated by MyBatis Generator.* This method sets the value of the database column user.CREATED_BY** @param createdBy the value for user.CREATED_BY** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public void setCreatedBy(String createdBy) {this.createdBy = createdBy;}/*** This method was generated by MyBatis Generator.* This method returns the value of the database column user.UPDATED_TIME** @return the value of user.UPDATED_TIME** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public Date getUpdatedTime() {return updatedTime;}/*** This method was generated by MyBatis Generator.* This method sets the value of the database column user.UPDATED_TIME** @param updatedTime the value for user.UPDATED_TIME** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public void setUpdatedTime(Date updatedTime) {this.updatedTime = updatedTime;}/*** This method was generated by MyBatis Generator.* This method returns the value of the database column user.UPDATED_BY** @return the value of user.UPDATED_BY** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public String getUpdatedBy() {return updatedBy;}/*** This method was generated by MyBatis Generator.* This method sets the value of the database column user.UPDATED_BY** @param updatedBy the value for user.UPDATED_BY** @mbg.generated Sat Mar 08 07:25:49 CST 2025*/public void setUpdatedBy(String updatedBy) {this.updatedBy = updatedBy;}@Overridepublic String toString() {return "User{" +"userId=" + userId +", userName='" + userName + '\'' +", age=" + age +", createdTime=" + createdTime +", createdBy='" + createdBy ;}
}

其他的类就不逐一介绍了,这里只列出User对象,后面会使用。

 

3.定义存储过程

这里的存储过程为了展示功能,使用了IN和OUT类型两种参数。

具体的功能为:根据输入的页面编号和页面数据量参数,返回总的页数和总数据量。同时返回查询的页面数据集合。

DELIMITER $$
CREATE PROCEDURE query_user_by_page(IN page_num INTEGER,IN page_size INTEGER,OUT total_count INTEGER,OUT total_page INTEGER
)
BEGINDECLARE start_pos INT;SET start_pos = (page_num - 1) * page_size;-- compute total count SELECT COUNT(1) INTO total_countFROM user;-- compute total pageSET total_page = CEILING(total_count/page_size);SELECT * FROM user LIMIT start_pos, page_size;
END
$$ DELIMITER ;

MySQL workbench console调用,检查procedure正确性

call query_user_by_page(2, 2, @total_count, @total_page);
select @total_count, @total_page;

 

小提示:MySQL 存储过程局部变量和全局变量区别和使用

1. 局部变量

局部变量是在存储过程或函数中声明的变量,其作用域仅限于该存储过程或函数内部。

声明局部变量

局部变量必须在存储过程的开头声明,且在 BEGIN 语句之后。使用 DECLARE 语句声明局部变量。

DELIMITER //CREATE PROCEDURE ExampleProcedure()
BEGINDECLARE var1 INT DEFAULT 0;  -- 声明一个整型变量,默认值为 0DECLARE var2 VARCHAR(50);    -- 声明一个字符串变量DECLARE var3 DATE;           -- 声明一个日期变量-- 变量赋值SET var2 = 'Hello, World!';SET var3 = '2025-04-14';-- 使用变量SELECT var1, var2, var3;
END //DELIMITER ;

2. 全局变量

全局变量的作用范围是整个数据库会话,可以在多个存储过程或会话中使用。MySQL 提供了一些预定义的全局变量,也可以通过 SET 语句设置自定义全局变量。

预定义的全局变量

MySQL 提供了一些系统全局变量,可以通过 SHOW VARIABLESSELECT @@variable_name 查看其值。

sql复制

SHOW VARIABLES LIKE 'max_connections';  -- 查看系统变量
SELECT @@max_connections;              -- 查看系统变量

自定义全局变量

可以通过 SET 语句设置自定义全局变量。自定义全局变量的作用范围是整个会话。

SET @global_var = 'Hello, Global!';  -- 设置全局变量DELIMITER //CREATE PROCEDURE UseGlobalVariable()
BEGINSELECT @global_var;  -- 在存储过程中使用全局变量
END //DELIMITER ;CALL UseGlobalVariable();  -- 调用存储过程

 

4.编写Mapper.xml中存储过程调用

<select id="queryUserByPage" statementType="CALLABLE" parameterType="map" resultType="com.derek.model.User">{call query_user_by_page(#{pageNum, mode=IN, javaType=INTEGER},#{pageSize, mode=IN, javaType=INTEGER},#{totalCount, mode=OUT, jdbcType=INTEGER},#{totalPage, mode=OUT, jdbcType=INTEGER})}
</select>

这里注意statementType选择“CALLABLE”,表示调用存储过程。一般使用map来传递IN, OUT 参数。

特别注意: 存储过程的名字要写对,不然查错误❌特别费劲。我曾经名字写错了,写成了调用方法的名字queryByPage。报错Parameter number 3 is not OUT parameter。被整得懵懵的,找了很久才发现错误。

5. Mapper.java中接口定义

public interface UserMapperExt extends UserMapper {List<User> queryUserByPage(Map<String,Object> map);}

这里使用Map<String,Object>来接收和存储OUT对象。

 

6.编写单元测试

package com.derek.mapper;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;public class UserMapperExtTest {private static SqlSession sqlSession;private static UserMapperExt userMapperExt;@BeforeAllpublic static void setUp() throws IOException {Reader reader = Resources.getResourceAsReader("mybatis-config.xml");sqlSession = new org.apache.ibatis.session.SqlSessionFactoryBuilder().build(reader).openSession();userMapperExt = sqlSession.getMapper(UserMapperExt.class);}@AfterAllpublic static void tearDown() {userMapperExt = null;sqlSession.close();}@Testpublic void testQueryByPage() {Map<String,Object> map = new HashMap<>();map.put("pageNum", 1);map.put("pageSize", 2);userMapperExt.queryUserByPage(map).forEach(System.out::println);sqlSession.commit();System.out.println("totalCount:" + map.get("totalCount"));System.out.println("totalPage:" + map.get("totalPage"));}}

我的数据库中User表有11条数据,查询接入如下: 

Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@76012793]
==>  Preparing: { call query_user_by_page( ?, ?, ?, ? ) }
==> Parameters: 1(Integer), 2(Integer)
<==    Columns: USER_ID, USER_NAME, AGE, CREATED_TIME, CREATED_BY, UPDATED_TIME, UPDATED_BY
<==        Row: 1, derek, 20, 2025-02-14 13:34:01, UNKNOWN, 2025-03-01 21:47:07, derek
<==        Row: 3, adore, 34, 2025-03-08 03:07:39, jack.zhang, 2025-03-08 03:07:39, jack.zhang
<==      Total: 2
<==    Updates: 0
User{userId=1, userName='derek', age=20, createdTime=Fri Feb 14 21:34:01 CST 2025, createdBy='UNKNOWN
User{userId=3, userName='adore', age=34, createdTime=Sat Mar 08 11:07:39 CST 2025, createdBy='jack.zhang
totalCount:11
totalPage:6
 

 到此为止,Mybatis3调用存储过程结束。

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/897764.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Uniapp组件 Textarea 字数统计和限制

Uniapp Textarea 字数统计和限制 在 Uniapp 中&#xff0c;可以通过监听 textarea 的 input 事件来实现字数统计功能。以下是一个简单的示例&#xff0c;展示如何在 textarea 的右下角显示输入的字符数。 示例代码 首先&#xff0c;在模板中定义一个 textarea 元素&#xff…

STM32 HAL库实战:轻松实现串口通信驱动蓝牙模块与ESP8266开发

STM32 HAL库实战&#xff1a;轻松实现串口通信驱动蓝牙模块与ESP8266开发 引言 STM32F103C8T6作为一款性能强劲的32位微控制器&#xff0c;广泛应用于各类嵌入式系统。本文将详细介绍如何使用STM32F103C8T6的HAL库进行串口通信&#xff0c;并展示如何通过串口驱动蓝牙模块&…

Discuz建站教程之论坛头部logo跳转链接怎么修改?

在修改头部logo跳转链接前&#xff0c;我们需要知道对应代码在哪个文件目录&#xff0c;进入宝塔或是服务器&#xff0c;找到文件&#xff1a;\template\default\common\header.htm&#xff0c;编辑器打开&#xff0c;搜索以下代码&#xff0c;大概在135行 <a href"{i…

python-leetcode-最大连续1的个数 III

1004. 最大连续1的个数 III - 力扣&#xff08;LeetCode&#xff09; 使用滑动窗口的方法来解决这个问题。 思路&#xff1a; 使用双指针&#xff08;滑动窗口&#xff09;&#xff0c;定义左右边界 left 和 right。维护窗口内最多包含 k 个 0。当窗口内的 0 超过 k 个时&…

Linux中grep、sed和awk常见用法总结

1.概述 Linux系统下&#xff0c;grep、sed和awk三个命令是最常用的、非常强大的文本处理工具&#xff0c;可以用于搜索、替换、过滤、排序等多种操作&#xff0c;掌握这三种工具的用法&#xff0c;可以大大提高我们在Linux下处理文本的效率。 2.grep命令 grep是一种非常常见…

基于Vue3的流程图绘制库

流程图组件的革命者&#xff0c;带你探索无限可能Vue Flow 基于Vue3的流程图绘制库

学习springboot-Bean管理(Bean 注册,Bean 扫描)

Bean 扫描 可以浏览下面的博客链接 &#xff1a;spring 学习 &#xff08;注解&#xff09;-CSDN博客 在学习spring 注解时&#xff0c;我们使用 Component &#xff0c;Service,Controller等 这样的注解&#xff0c;将目标类信息&#xff0c;传递给IOC容器&#xff0c;为其创…

spring中将yaml文件转换为Properties

文章目录 一 &#xff0c;概述二&#xff0c;源码 一 &#xff0c;概述 借助于spring框架&#xff0c;将yaml文件转换为Properties 二&#xff0c;源码 import java.util.Properties;import org.junit.Test; import org.springframework.beans.factory.config.YamlPropertie…

c++ 中的float和double 的区别 开发过程中使用哪个更好

在 C 中&#xff0c;float 和 double 都是用于表示浮点数的数据类型&#xff0c;但它们在精度、存储空间和性能方面有所不同。 1. float 和 double 的主要区别 特性floatdouble占用内存4 字节&#xff08;32 位&#xff09;8 字节&#xff08;64 位&#xff09;精度约 6-7 位有…

OpenAI智能体初探:使用 OpenAI Responses API 在 PDF 中实现检索增强生成(RAG)

大家好,我是大 F,深耕AI算法十余年,互联网大厂技术岗。 知行合一,不写水文,喜欢可关注,分享AI算法干货、技术心得。 欢迎关注《大模型理论和实战》、《DeepSeek技术解析和实战》,一起探索技术的无限可能! 引子 在信息爆炸的时代,从大量 PDF 文档中快速准确地检索信息…

【MySQL】基本操作 —— DDL

目录 DDLDDL 常用操作对数据库的常用操作查看所有数据库创建数据库切换、显示当前数据库删除数据库修改数据库编码 对表的常用操作创建表数据类型数值类型日期和时间类型字符串类型 查看当前数据库所有表查看指定表的创建语句查看指定表结构删除表 对表结构的常用操作给表添加字…

工厂模式加策略模式 -- 具体实现

这里写目录标题 定义接口定义抽象类定义主处理器分支处理器定义工厂demo 定义接口 public interface EntityHandler extends InitializingBean {MatchContentDTO match(MatchEntityDTO matchEntityDTO);String supportEntityType(); }定义抽象类 public abstract class Abstr…

基于Spring Boot的网上宠物店系统的设计与实现(LW+源码+讲解)

专注于大学生项目实战开发,讲解,毕业答疑辅导&#xff0c;欢迎高校老师/同行前辈交流合作✌。 技术范围&#xff1a;SpringBoot、Vue、SSM、HLMT、小程序、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、安卓app、大数据、物联网、机器学习等设计与开发。 主要内容&#xff1a;…

PHPCMS V9 登录加密改造

要改造 phpcms 的后台登录&#xff0c;使其前端使用加密方式提交&#xff0c;后端解密&#xff0c;你可以采用 RSA 非对称加密 或 AES 对称加密 方式来增强安全性。 方案设计 前端加密 生成公私钥对&#xff08;推荐使用 RSA&#xff09;。前端使用公钥加密密码&#xff0c;然…

LeetCode 滑动数组统计+至少 2962. 统计最大元素出现至少 K 次的子数组

2962. 统计最大元素出现至少 K 次的子数组 给你一个整数数组 nums 和一个 正整数 k 。 请你统计有多少满足 「 nums 中的 最大 元素」至少出现 k 次的子数组&#xff0c;并返回满足这一条件的子数组的数目。 子数组是数组中的一个连续元素序列。 示例 1&#xff1a; 输入&#…

FANUC机器人几种常用的通讯网络及接口

FANUC机器人几种常用的通讯网络及接口 Devicenet 网络通讯接口&#xff0c;接口为5针线 (规定用的机架为 81-84&#xff09; PROFIBUS 网络通讯接口&#xff0c;针脚为2针&#xff08;规定用的机架为 67&#xff09; Intemet 网络通讯接口&#xff08;常用的网线接口&#xf…

CentOS8+Zabbix7.2.4解决中文显示问题

#cd /usr/share/zabbix/ui/include/ #grep graphfont defines.inc.php define(‘ZBX_GRAPH_FONT_NAME’, ‘graphfont’); // font file name define(‘ZBX_FONT_NAME’, ‘graphfont’); #ll /usr/share/zabbix/ui/assets/fonts/graphfont.ttf lrwxrwxrwx. 1 root root 36 3…

AI自动化编程初探

先说vscodeclinemodelscope方案&#xff0c;后面体验trae或者cursor再写写其它的。vscode和trae方案目前来说是免费的&#xff0c;cursor要用claud需要付费&#xff0c;而且不便宜&#xff0c;当然效果可能是最好的。 vscode方案&#xff0c;我的经验是最好在ubuntu上&#xff…

101.在 Vue 3 + OpenLayers 使用 declutter 避免文字标签重叠

1. 前言 在使用 OpenLayers 进行地图开发时&#xff0c;我们经常需要在地图上添加点、线、区域等图形&#xff0c;并给它们附加文字标签。但当地图上的标注较多时&#xff0c;文字标签可能会发生重叠&#xff0c;导致用户无法清晰地查看地图信息。 幸运的是&#xff0c;OpenL…

18天 - 常见的 HTTP 状态码有哪些?HTTP 请求包含哪些内容,请求头和请求体有哪些类型?HTTP 中 GET 和 POST 的区别是什么?

常见的 HTTP 状态码有哪些&#xff1f; HTTP 状态码用于指示服务器对客户端请求的响应结果&#xff0c;常见的 HTTP 状态码可以分为以下几类&#xff1a; 1. 信息类&#xff08;1xx&#xff09; 100 Continue&#xff1a;客户端应继续发送请求。101 Switching Protocols&…