Spring--mybatis call stored procedure

1. Introduction to stored procedures

Our commonly used operation database language SQL statement needs to be compiled first and then executed when executed, and the stored procedure (Stored Procedure) is a set of SQL statements to complete a specific function, which is stored in the database after compilation, the user specifies The name of the stored procedure and given parameters (if the stored procedure has parameters) to call and execute it.

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

2. Advantages of stored procedures

  1. Stored procedures enhance the functionality and flexibility of SQL language. Stored procedures can be written in flow control statements, which have great flexibility 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, then the stored procedure is much faster than batch processing. Because the stored procedure is pre-compiled. When querying a stored procedure for the first time, the optimizer analyzes and optimizes it and gives an execution plan that is eventually stored in the system table. The batched Transaction-SQL statements must be compiled and optimized each time they are run, which is relatively slow.

  4. Stored procedures can reduce network traffic too. For the operation of the same database object (such as query, modify), 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 in the network Statement, which greatly increases network traffic and reduces network load.

  5. Stored procedures can be fully utilized as a security mechanism. The system administrator can limit the access rights of the corresponding data by restricting the permissions of a certain stored procedure, avoiding the access of unauthorized users to the data, and ensuring the security of the data.

3. Disadvantages of stored procedures

  1. Not easy to maintain, once the logic changes, it is troublesome to modify
  2. If the person who writes this stored procedure leaves, it is estimated that it will be a disaster for the person who takes over her code, because others will have to read your program logic and your stored logic. Not conducive to expansion.
  3. The biggest disadvantage! 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. The syntax of the stored procedure

4.1 Create a stored procedure

create procedure sp_name()
begin
.........
end
  • 1
  • 2
  • 3
  • 4
  • 5

4.2 Calling a stored procedure

call sp_name()
  • 1

Note: You must add parentheses after the name of the stored procedure, even if the stored procedure does not pass parameters

4.3 Delete stored procedure

drop procedure sp_name//
  • 1

Note: You cannot delete another stored procedure in one stored procedure, you can only call another stored procedure

4.4 Other common commands

show procedure status
  • 1

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

show create procedure sp_name
  • 1

Display detailed information about a MySQL stored procedure

5. Case implementation of MyBatis calling MySQL stored procedure

5.1 Brief description of the case

The case is mainly realized by a simple statistics of the total number of devices with a certain name.

5.2 Creation of database tables

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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

5.3 Creating a stored procedure

Take the name of the device as the input parameter and the total number of devices counted 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 ;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

5.4 Mybatis calls MySQL stored procedure

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

3. Implementation of DeviceDAO

package com.lidong.axis2demo;

public interface DeviceDAO {

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

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

4. Implementation of Mapper

<?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>  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Note: statementType = ”CALLABLE” must be CALLABLE, tell MyBatis to execute the stored procedure, otherwise it will report an 
Exception in thread “main” org.apache.ibatis.exceptions.PersistenceException

mode = IN input parameter mode = OUT output parameter jdbcType is the field type defined by the database. 
Writing Mybatis in this way 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());
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

result 
Write a picture description here

Published 7 original articles · 69 praises · 200,000+ views

Guess you like

Origin blog.csdn.net/u014320421/article/details/80003830