(五)MyBatis 调用Mysql存储过程

1.准备数据库和建表过程

create table p_user(  
    id int primary key auto_increment,  
    name varchar(10),
    sex char(2)
); 

insert into p_user(name,sex) values('A',"男");  
insert into p_user(name,sex) values('B',"女");  
insert into p_user(name,sex) values('C',"男");  

-- 创建存储过程(查询得到男性或女性的数量, 如果传入的是0就女性否则是男性)
DELIMITER $
CREATE PROCEDURE mybatis.ges_user_count(IN sex_id INT, OUT user_count INT)
BEGIN  
IF sex_id=0 THEN
SELECT COUNT(*) FROM mybatis.p_user WHERE p_user.sex='女' INTO user_count;
ELSE
SELECT COUNT(*) FROM mybatis.p_user WHERE p_user.sex='男' INTO user_count;
END IF;
END 
$

-- 调用存储过程
DELIMITER ;
SET @user_count = 0;
CALL mybatis.ges_user_count(1, @user_count);
SELECT @user_count;

2.userMapper.xml:






    


    

    
    
        
        
    

3.mybatis.xml






    
    
    
    
        
            
            
            
            
            
            
            
            
            
                
                
                
                
                
            
        
    
    
    
        
    
    
    
        
    


4测试代码如下:


    @Test
    public void Process(){
        SqlSessionFactory factory=MybatisUtils.getFactory();
        SqlSession session=factory.openSession(true);
        /**
         * 映射sql的标识字符串,
         * me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,
         * getUserCount是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
         */
        String statement = "mapper.userMapper.getUserCount";//映射sql的标识字符串
        Map parameterMap = new HashMap();
        parameterMap.put("sexid", 1);
        parameterMap.put("usercount", -1);
        session.selectOne(statement, parameterMap);
        Integer result = parameterMap.get("usercount");
        System.out.println(result);
        session.close();
    }

MybatisUtils.java

package com.flyz;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtils {
    public static SqlSessionFactory getFactory(){
        String resource="mybatis.xml";

        //加载mybatis 的配置文件(它也加载关联的映射文件)
        InputStream is=MybatisUtils.class.getClassLoader().getResourceAsStream(resource);
        //构建sqlSession 的工厂
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
        return factory;
    }
}

测试结果如下:


hhhhh.png

你可能感兴趣的:((五)MyBatis 调用Mysql存储过程)