Mybatis3 调用存储过程

news2025/3/17 11:22:21

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;
    }

    @Override
    public 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
)
BEGIN
	DECLARE start_pos INT;
	SET start_pos = (page_num - 1) * page_size;
	
    -- compute total count 
    SELECT COUNT(1) INTO total_count
    FROM user;
    
    -- compute total page
    SET 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()
BEGIN
    DECLARE var1 INT DEFAULT 0;  -- 声明一个整型变量,默认值为 0
    DECLARE 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()
BEGIN
    SELECT @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;

    @BeforeAll
    public 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);
    }

    @AfterAll
    public static void tearDown() {
        userMapperExt = null;
        sqlSession.close();
    }

    @Test
    public 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.coloradmin.cn/o/2316587.html

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

相关文章

HiPixel开源AI驱动的图像超分辨率的原生macOS 应用程序,使用 SwiftUI 构建并利用 Upscayl 强大的 AI 模型

一、软件介绍 文末提供程序和源码下载 HiPixel是一个开源程序基于SwiftUI构建的macOS原生应用程序&#xff0c;用于AI驱动的图像超分辨率&#xff0c;并利用Upscayl的强大AI模型。 二、软件特征 具有 SwiftUI 界面的原生 macOS 应用程序使用 AI 模型进行高质量图像放大通过 G…

缓存和客户端数据存储体系(Ark Data Kit)--- 应用数据持久化(首选项持久化、K-V、关系型数据库)持续更新中...

Core File Kit做怎删改查操作不便&#xff0c;用Ark Data Kit。 功能介绍 ArkData &#xff08;方舟数据管理&#xff09;为开发者提供数据存储、数据管理和数据同步能力&#xff0c;比如联系人应用数据可以保存到数据库中&#xff0c;提供数据库的安全、可靠以及共享访问等管…

本地部署OpenManus及原理介绍

概述&#xff1a; 最近Minaus特别火&#xff0c;随后开源社区就有项目尝试复刻Minaus&#xff0c;项目名称为OpenManus&#xff0c;原理是用推理模型为决策者&#xff0c;将我们输入的问题进行分解后调用本地工具执行。 OpenManus安装&#xff1a; 本人在Ubuntu桌面版本上安装…

高效手机检测:视觉分析技术的优势

在当今社会&#xff0c;手机已成为人们日常生活和工作中不可或缺的工具。然而&#xff0c;在某些特定场合&#xff0c;如考场、工作场所等&#xff0c;手机的使用却可能带来负面影响。因此&#xff0c;如何有效监测和防止在这些场合偷用手机的行为&#xff0c;成为了一个亟待解…

Spring Boot配置类原理、Spring Boot核心机制理解,以及实现自动装置的底层原理

目的:从底层源码角度分析 Spring Boot 配置类以及自动装载的底层原理 文章目录 1. Spring Boot 配置类实现自动装载1.1 @Configuration注解1.2 @Configuration 注解完成 bean 注入流程图1.3 @ConfigurationProperties注解赋值2. Spring Boot的核心机制:自动装配2.1 @SpringBo…

01-Canvas-使用fabric初始

fabric官网&#xff1a; https://fabric5.fabricjs.com/demos/ 创建画布并绘制 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-sca…

树莓派 连接 PlutoSDR 教程

在树莓派5上安装PlutoSDR&#xff08;ADALM-Pluto&#xff09;的驱动程序&#xff0c;主要需要安装相关的库和工具&#xff0c;以便与PlutoSDR通信&#xff0c;比如libiio和libad9361&#xff0c;并确保系统能够识别设备。由于树莓派5运行的是基于Linux的系统&#xff08;通常是…

Git使用(二)--如何配置 GitHub 远程仓库及本地 Git 环境

在日常的开发过程中&#xff0c;使用版本控制工具 Git 是一个非常重要的技能&#xff0c;特别是对于管理和协作开发。通过 GitHub&#xff0c;我们可以轻松地进行代码版本管理和共享。这篇博客将带您一步步学习如何配置 Git 环境并将本地仓库与 GitHub 远程仓库连接起来。 一、…

在Pycharm配置conda虚拟环境的Python解释器

〇、前言 今天在配置python解释器时遇到了这样的问题 经过一下午自行摸索、上网搜寻后&#xff0c;终于找到的解决的方案&#xff0c;遂将该方法简要的记录下来&#xff0c;以备后用&#xff0c;并希望能帮助到有同样问题或需求的朋友:) 我所使用的软件的版本如下&#xff0c;假…

零基础keil:设置注释快捷键

1.打开快捷键设置&#xff1a; 在Keil中&#xff0c;选择菜单栏中的“Settings”&#xff0c;然后选择“Shortcuts”来打开快捷键设置界面。 2.选择注释命令&#xff1a; 在快捷键设置界面中&#xff0c;找到与注释相关的命令&#xff0c;如“Comment Selection”&#xff0…

Java中关于Optional的 orElse 操作,以及 orElse 与 orElseGet 的区别

文章目录 1. 大概说明2. 详细分析2.1 .orElse 操作2.2 .orElse 的作用&#xff1a;避免空指针异常2.3 为什么要用&#xff1f;2.4 orElseGet如何使用2.5 orElse和orElseGet的区别 1. 大概说明 这篇文章的目的是为了说明&#xff1a; orElse 如何使用orElseGet 如何使用两者的…

TCP/IP协议中三次握手(Three-way Handshake)与四次挥手(Four-way Wave)

TCP/IP协议中三次握手&#xff08;Three-way Handshake&#xff09;与四次挥手&#xff08;Four-way Wave&#xff09; 一、TCP三次握手&#xff08;Three-way Handshake&#xff09;二、TCP四次挥手&#xff08;Four-way Wave&#xff09;三、常见问题解答总结为什么三次握手不…

python学智能算法(八)|决策树

【1】引言 前序学习进程中&#xff0c;已经对KNN邻近算法有了探索&#xff0c;相关文章链接为&#xff1a; python学智能算法&#xff08;七&#xff09;|KNN邻近算法-CSDN博客 但KNN邻近算法有一个特点是&#xff1a;它在分类的时候&#xff0c;不能知晓每个类别内事物的具…

【QT:控件】

目录 控件状态&#xff1a;​编辑 geometry : window frame windowlcon: qrc机制 qrc的使用方式&#xff1a; window opacity cursor font: ToolTip focusPolicy: styleSheet: 按钮类控件&#xff1a; PushButton: 给按钮添加图标&#xff1a; 给按钮添加快捷键…

Python(最新版)集成开发环境PyCharm下载安装详细教程

Python 下载和安装 1.进入Python官网 Download Python | Python.org&#xff0c;点击Downloads&#xff0c;这里以Windows为例 2.选择下载Python 3.13.2 Windows 64位的版本。注意&#xff1a;不能在Windows 7 或更早的版本上使用。 3.打开文件&#xff0c;会自动出现安装界…

uniapp 实现的步进指示器组件

采用 uniapp 实现的一款步进指示器组件&#xff0c;展示业务步骤进度等内容&#xff0c;对外提供“前进”、“后退”方法&#xff0c;让用户可高度自定义所需交互&#xff0c;适配 web、H5、微信小程序&#xff08;其他平台小程序未测试过&#xff0c;可自行尝试&#xff09; 可…

大模型-提示词调优

什么是提示词 提示词&#xff08;Prompt&#xff09;在大模型应用中扮演着关键角色&#xff0c;它是用户输入给模型的一段文本指令 。简单来说&#xff0c;就是我们向大模型提出问题、请求或描述任务时所使用的文字内容。例如&#xff0c;当我们想让模型写一篇关于春天的散文&a…

继承知识点—详细

一&#xff1a;普通写法 package extend_;public class Extends01 {public static void main(String[] args) {Pubil pubil new Pubil();pubil.name"小明";pubil.age18;pubil.testing();pubil.setScore(60);pubil.showInfo();System.out.println("-----------…

设备管理VTY(Telnet、SSH)

实验目的&#xff1a;物理机远程VTY通过telnet协议登录AR1,ssh协议登录AR2和sw 注意配置Cloud1&#xff1a; 注意&#xff01;&#xff01;博主的物理机VMnet8--IP&#xff1a;192.168.160.1&#xff0c;所以AR1路由0/0/0端口才添加IP&#xff1a;192.168.160.3&#xff0c;每个…

Linux 中 Git 使用指南:从零开始掌握版本控制

目录 1. 什么是 Git&#xff1f; Git 的核心功能&#xff1a; 2. Git 的安装 Ubuntu/Debian 系统&#xff1a; 验证安装&#xff1a; 3.gitee库 4. Git 的首次配置 配置用户名和邮箱&#xff1a; 查看配置&#xff1a; 5. Git 的基本使用 初始化仓库 添加文件到暂存区…