1. 程式人生 > >mybatis 呼叫儲存過程

mybatis 呼叫儲存過程

要求:查詢得到男性或女性的數量如果傳入的是0就女性否則是男性

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;

public class User {
	private String id;
	private String name;
	private String sex;
     //set和get方法
}
userMapper.xml
<?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.lx.test7.userMapper"> 
     
     <select id="getUserCount" parameterMap="getUserMap" statementType="CALLABLE">
      
       CALL hibernate1.ges_user_count(?,?);
     
     </select>    
      
      <parameterMap type="java.util.Map" id="getUserMap">
          <parameter property="sexid"  mode="IN" jdbcType="INTEGER"/>
          <parameter property="usercount" mode="OUT"  jdbcType="INTEGER"/>
      </parameterMap>
      
	</mapper>

測試類:
package com.lx.test7;

import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import com.lx.bean.Classes;
import com.lx.utils.FactoryUtil;

public class Test7 {

	@Test
	public void test1()
	{
		SqlSessionFactory factory = FactoryUtil.getFactory();
		
		SqlSession session = factory.openSession();
	
		String statement = "com.lx.test7.userMapper.getUserCount";
		
		Map<String,Integer> parameter = new HashMap<String, Integer>();
		
		parameter.put("sexid", 0);
		parameter.put("usercount", -1);
		
		session.selectOne(statement, parameter);
		
	   int count = 	parameter.get("usercount");
	   
	   System.out.println(count);
		
		session.close();
	}
	
	
}