


Detailed explanation of examples of calling MySQL stored procedures through Mybatis
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
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.
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.
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.
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.
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
It is not easy to maintain. Once the logic changes, it will be troublesome to modify
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.
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
4.2 Call stored procedure
call sp_name()
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//
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
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
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;
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 ;
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>
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; } }
3. Implementation of DeviceDAO
package com.lidong.axis2demo; public interface DeviceDAO { /** * 调用存储过程 获取设备的总数 * @param devicePOJO */ public void count(DevicePOJO devicePOJO); }
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>
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()); } }
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!

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software