


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!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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.

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.

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.

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

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.

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).

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
