Home Database Mysql Tutorial Detailed explanation of examples of calling MySQL stored procedures through Mybatis

Detailed explanation of examples of calling MySQL stored procedures through Mybatis

May 15, 2018 pm 05:43 PM
mybatis mysql stored procedure

This article mainly introduces the implementation of MySQL stored procedures called through Mybatis, which has certain reference value. Interested friends can refer to it.

1. Introduction to stored procedures

Our commonly used operating database language SQL statements need to be compiled first and then executed when executed, while stored procedures (Stored Procedure ) is a set of SQL statements designed to accomplish specific functions. They are compiled and stored in the database. The user calls and executes the stored procedure by specifying the name of the stored procedure and giving parameters (if the stored procedure has parameters).

A stored procedure is a programmable function that is created and saved in the database. It can consist of SQL statements and some special control structures. Stored procedures are useful when you want to perform the same function on different applications or platforms, or encapsulate specific functionality. Stored procedures in a database can be seen as a simulation of the object-oriented approach in programming. It allows control over how data is accessed.

2. Advantages of stored procedures

  1. Stored procedures enhance the functionality and flexibility of the SQL language. Stored procedures can be written using flow control statements, are highly flexible, and can complete complex judgments and more complex operations.

  2. Stored procedures allow standard components to be programmed. After a stored procedure is created, it can be called multiple times in the program without having to rewrite the SQL statement of the stored procedure. And database professionals can modify stored procedures at any time without affecting the application source code.

  3. Stored procedures can achieve faster execution speed. If an operation contains a large amount of Transaction-SQL code or is executed multiple times, the stored procedure will execute much faster than batch processing. Because stored procedures are precompiled. When a stored procedure is run for the first time, the query is analyzed and optimized by the optimizer and an execution plan is finally stored in the system table. The batch Transaction-SQL statement must be compiled and optimized every time it is run, and the speed is relatively slower.

  4. Stored procedures can reduce network traffic. For operations on the same database object (such as query, modification), if the Transaction-SQL statement involved in this operation is organized into a stored procedure, then when the stored procedure is called on the client computer, only the call is transmitted over the network statements, thereby greatly increasing network traffic and reducing network load.

  5. Stored procedures can be fully utilized as a security mechanism. By restricting the permissions for executing a certain stored procedure, the system administrator can limit the access permissions of the corresponding data, avoid unauthorized users from accessing the data, and ensure the security of the data.

3. Disadvantages of stored procedures

  1. It is not easy to maintain. Once the logic changes, it will be troublesome to modify

  2. If the person who wrote this stored procedure resigns, it will probably be a disaster for the person who takes over her code, because others will have to understand your program logic and your storage logic. Not conducive to expansion.

  3. The biggest shortcoming! Although stored procedures can reduce the amount of code and improve development efficiency. But one very fatal thing is that it consumes too much performance.

4. Syntax of stored procedure

4.1 Create stored procedure

create procedure sp_name()
begin
.........
end
Copy after login

4.2 Call stored procedure

call sp_name()
Copy after login

Note: Parentheses must be added after the stored procedure name, even if the stored procedure has no parameters to pass

4.3 Delete stored procedures

drop procedure sp_name//
Copy after login

Note: You cannot delete another stored procedure in one stored procedure. Only another stored procedure can be called

4.4 Other common commands

show procedure status
Copy after login

Display the basic information of all stored procedures in the database, including the database to which it belongs, the name of the stored procedure, the creation time, etc.

show create procedure sp_name
Copy after login

Display detailed information of a certain MySQL stored procedure

5. Case implementation of MyBatis calling MySQL stored procedure

5.1 Brief description of the case

The case is mainly implemented by simply counting the total number of devices with a certain name.

5.2 Creation of database table

DROP TABLE IF EXISTS `cus_device`;
CREATE TABLE `cus_device` (
 `device_sn` varchar(20) NOT NULL COMMENT '设备编号',
 `device_cat_id` int(1) DEFAULT NULL COMMENT '设备类型',
 `device_name` varchar(64) DEFAULT NULL COMMENT '设备名称',
 `device_type` varchar(64) DEFAULT NULL COMMENT '设备型号',
 PRIMARY KEY (`device_sn`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy after login

5.3 Creation of stored procedure

Take the name of the device as the input parameter and the total number of counted devices as the output parameter

DROP PROCEDURE IF EXISTS `countDevicesName`;
DELIMITER ;;
CREATE PROCEDURE `countDevicesName`(IN dName VARCHAR(12),OUT deviceCount INT)
BEGIN
SELECT COUNT(*) INTO deviceCount FROM cus_device WHERE device_name = dName;

END
;;
DELIMITER ;
Copy after login

5.4 Mybatis calls MySQL stored procedures

1. mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE configuration PUBLIC  
  "-//mybatis.org//DTD Config 3.0//EN" 
  "http://mybatis.org/dtd/mybatis-3-config.dtd"> 
<configuration> 

  <settings>
  <!-- 打印查询语句 -->
    <setting name="logImpl" value="STDOUT_LOGGING" />
  </settings>
  <!-- 配置别名 --> 
  <typeAliases> 
    <typeAlias type="com.lidong.axis2demo.DevicePOJO" alias="DevicePOJO" />  
  </typeAliases> 

  <!-- 配置环境变量 --> 
  <environments default="development"> 
    <environment id="development"> 
      <transactionManager type="JDBC" /> 
      <dataSource type="POOLED"> 
        <property name="driver" value="com.mysql.jdbc.Driver" /> 
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/bms?characterEncoding=GBK" /> 
        <property name="username" value="root" /> 
        <property name="password" value="123456" /> 
      </dataSource> 
    </environment> 
  </environments> 

  <!-- 配置mappers --> 
  <mappers> 
    <mapper resource="com/lidong/axis2demo/DeviceMapper.xml" /> 
  </mappers> 

</configuration>
Copy after login

2. CusDevice.java

public class DevicePOJO{

   private String devoceName;//设备名称
   private String deviceCount;//设备总数


  public String getDevoceName() {
    return devoceName;
  }
  public void setDevoceName(String devoceName) {
    this.devoceName = devoceName;
  }
  public String getDeviceCount() {
    return deviceCount;
  }
  public void setDeviceCount(String deviceCount) {
    this.deviceCount = deviceCount;
  }
}
Copy after login

3. Implementation of DeviceDAO

package com.lidong.axis2demo;

public interface DeviceDAO {

  /**
   * 调用存储过程 获取设备的总数
   * @param devicePOJO
   */
  public void count(DevicePOJO devicePOJO);

}
Copy after login

4.Mapper implementation

<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lidong.axis2demo.DeviceDAO">

  <resultMap id="BaseResultMap" type="CusDevicePOJO">
    <result column="device_sn" property="device_sn" jdbcType="VARCHAR" />
  </resultMap>

  <sql id="Base_Column_List">
    device_sn, device_name,device_mac
  </sql>

  <select id="count" parameterType="DevicePOJO" useCache="false"
    statementType="CALLABLE"> 
    <![CDATA[ 
    call countDevicesName(
    #{devoceName,mode=IN,jdbcType=VARCHAR},
    #{deviceCount,mode=OUT,jdbcType=INTEGER});
    ]]>
  </select>
</mapper>
Copy after login

Note: statementType="CALLABLE" must be CALLABLE, telling MyBatis to execute the stored procedure, otherwise an error will be reported
Exception in thread "main" org.apache.ibatis. exceptions.PersistenceException

mode=IN The input parameter mode=OUT and the output parameter jdbcType is the field type defined by the database.
Writing like this Mybatis will help us automatically backfill the output deviceCount value.

5. Test

package com.lidong.axis2demo;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
 * MyBatis 执行存储过程
 * @author Administrator
 *
 */
public class TestProduce {

  private static SqlSessionFactoryBuilder sqlSessionFactoryBuilder; 
  private static SqlSessionFactory sqlSessionFactory; 
  private static void init() throws IOException { 
    String resource = "mybatis-config.xml"; 
    Reader reader = Resources.getResourceAsReader(resource); 
    sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); 
    sqlSessionFactory = sqlSessionFactoryBuilder.build(reader); 
  } 

  public static void main(String[] args) throws Exception {
    testCallProduce();
  }

  /**
   * @throws IOException
   */
  private static void testCallProduce() throws IOException {
    init();
    SqlSession session= sqlSessionFactory.openSession(); 
    DeviceDAO deviceDAO = session.getMapper(DeviceDAO.class); 
    DevicePOJO device = new DevicePOJO(); 
    device.setDevoceName("设备名称"); 
    deviceDAO.count(device);
    System.out.println("获取"+device.getDevoceName()+"设备的总数="+device.getDeviceCount());
  }

}
Copy after login

Result


The above is the detailed content of Detailed explanation of examples of calling MySQL stored procedures through Mybatis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

How to fill in mysql username and password How to fill in mysql username and password Apr 08, 2025 pm 07:09 PM

To fill in the MySQL username and password: 1. Determine the username and password; 2. Connect to the database; 3. Use the username and password to execute queries and commands.

Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

How to copy and paste mysql How to copy and paste mysql Apr 08, 2025 pm 07:18 PM

Copy and paste in MySQL includes the following steps: select the data, copy with Ctrl C (Windows) or Cmd C (Mac); right-click at the target location, select Paste or use Ctrl V (Windows) or Cmd V (Mac); the copied data is inserted into the target location, or replace existing data (depending on whether the data already exists at the target location).

Understand ACID properties: The pillars of a reliable database Understand ACID properties: The pillars of a reliable database Apr 08, 2025 pm 06:33 PM

Detailed explanation of database ACID attributes ACID attributes are a set of rules to ensure the reliability and consistency of database transactions. They define how database systems handle transactions, and ensure data integrity and accuracy even in case of system crashes, power interruptions, or multiple users concurrent access. ACID Attribute Overview Atomicity: A transaction is regarded as an indivisible unit. Any part fails, the entire transaction is rolled back, and the database does not retain any changes. For example, if a bank transfer is deducted from one account but not increased to another, the entire operation is revoked. begintransaction; updateaccountssetbalance=balance-100wh

See all articles