JAV A通过MyBatis调用MySql存储过程和函数1.引言无论是采用SPRING MVC框架开发WEB画面,还是开发需按一定时间间隔执行的批处理,都可能要调用数据库的存储过程或函数。
其间调用参数设置不正会浪费大量调试时间初学者甚至放弃使用存储过程。
本文记录了通过MyBatis调用MySql存储过程和函数的具体参数设置内容,供参考。
2.MySql存储过程例/*全公司员工下一年度带薪休假一发赋予处理*/CREATE DEFINER=`DBuser`@`%` PROCEDURE `paid_vacation_compute `( OUT p_返回值 INT(11) ,INOUT p_员工号 CHAR(3) ,p_操作者ID VARCHAR(3))PROC_START:BEGIN/* 变量声明 */DECLARE done INT; #异常退出控制变量DECLARE empNo CHAR(3); #员工号DECLARE dateHire date; #分公司就职日DECLARE workYears INT; #集团内工作年数DECLARE lastYearRemainDays FLOAT; #昨年残日数(允许以小时为单位休假)DECLARE nowYearleaveDays FLOAT; #今年休暇日数(允许以小时为单位休假)DECLARE elapseYear INT; #入集团经过年度数/* 游标声明 */#上年带薪休假数据DECLARE staffPaidVacationDaysCur CURSOR FORSELECT a.EMP_NO, #员工号a.DATE_HIRE, #入职日期a.WORK_YEARS, #工作年限b.REMAIN_DAYS # 上年带薪休假应休但未休残日数FROM T_EMPLOYEE AS a,T_PAID_VACATION AS bWHERE a. EMP_NO = b. EMP_NO/* 程序退出规定声明 */DECLARE CONTINUE HANDLER FOR NOT FOUND SET SET done = 1;DECLARE EXIT HANDLER FOR SQLWARNING SET done = 2;DECLARE CONTINUE HANDLER FOR SQLEXCEPTIONBEGINSET done = 3;ROLLBACK; #SQL异常回滚END;/* 1.输入参数妥当性检查 */IF (p_操作者 IS NULL OR p_操作者 = '') THENSET p_返回值 = 9;LEAVE PROC_START;END IF;SET done = 0;START TRANSACTION;loop_label:LOOP# 读入一条记录, 代入到各个变量中FETCH staffPaidVacationDaysCurINTO empNo, #员工号dateHire, #就职日workYears, #集团内工作年数lastYearRemainDays #昨年残日数;IF done = 1 THENLEAVE loop_label;END IF;/*根据集团内工作年限+分公司就职年限计算下一年度带薪天数*/ SET elapseYear = YEAR(current_timestamp)- Year(dateHire)+ workYears;IF elapseYear = 0 THENSET nowYearLeaveDays = 10;ELSEIF elapseYear = 1 THENSET nowYearLeaveDays = 11;ELSEIF elapseYear = 2 THENSET nowYearLeaveDays = 12;ELSEIF elapseYear = 3 THENSET nowYearLeaveDays = 14;ELSEIF elapseYear = 4 THENSET nowYearLeaveDays = 16;ELSEIF elapseYear = 5 THENSET nowYearLeaveDays = 18;ELSEIF elapseYear >= 6 THENSET nowYearLeaveDays = 20;END IF;SET done = 0;SET p_员工号= empNo;UPDATE T_PAID_VACATIONSETLAST_YEAR_REMAIN_DAYS = lastYearRemainDays,THIS_YEAR_BASE_DAYS = nowYearLeaveDays,UPDATE_DATETIME = current_timestamp,UPDATE_USER_ID = 'SYS',UPDATE_TERMINAL_ID = 'MANUAL'WHERE EMP_NO = CONVERT(empNo USING binary);IF done = 3 THENSET p_返回值 = 6;LEAVE PROC_START;END IF;END LOOP;COMMIT;END3.MySql函数例CREATE DEFINER=`DBuser`@`%` FUNCTION ` paid_vacation_compute `( p_员工号 CHAR(3) ,p_操作者ID VARCHAR(3))) RETURNS int(11)BEGIN/* 变量声明 */DECLARE done INT; #异常退出控制变量DECLARE empNo CHAR(3); #员工号DECLARE dateHire date; #分公司就职日DECLARE workYears INT; #集团内工作年数DECLARE lastYearRemainDays FLOAT; #昨年残日数(允许以小时为单位休假)DECLARE nowYearleaveDays FLOAT; #今年休暇日数(允许以小时为单位休假)DECLARE elapseYear INT; #入集团经过年度数/* 游标声明 */#上年带薪休假数据DECLARE staffPaidVacationDaysCur CURSOR FORSELECT a.EMP_NO, #员工号a.DATE_HIRE, #入职日期a.WORK_YEARS, #工作年限b.REMAIN_DAYS # 上年带薪休假应休但未休残日数FROM T_EMPLOYEE AS a,T_PAID_VACATION AS bWHERE a. EMP_NO = b. EMP_NO/* 程序退出规定声明 */DECLARE CONTINUE HANDLER FOR NOT FOUND SET SET done = 1;DECLARE EXIT HANDLER FOR SQLWARNING SET done = 2;DECLARE CONTINUE HANDLER FOR SQLEXCEPTIONBEGINSET done = 3;ROLLBACK; #SQL异常回滚END;/* 1.输入参数妥当性检查 */IF (p_操作者 IS NULL OR p_操作者 = '') THENRETURN 9;END IF;SET done = 0;START TRANSACTION;loop_label:LOOP# 读入一条记录, 代入到各个变量中FETCH staffPaidVacationDaysCurINTO empNo, #员工号dateHire, #就职日workYears, #集团内工作年数lastYearRemainDays #昨年残日数;IF done = 1 THENLEAVE loop_label;END IF;/*根据集团内工作年限+分公司就职年限计算下一年度带薪天数*/ SET elapseYear = YEAR(current_timestamp)- Year(dateHire)+ workYears;IF elapseYear = 0 THENSET nowYearLeaveDays = 10;ELSEIF elapseYear = 1 THENSET nowYearLeaveDays = 11;ELSEIF elapseYear = 2 THENSET nowYearLeaveDays = 12;ELSEIF elapseYear = 3 THENSET nowYearLeaveDays = 14;ELSEIF elapseYear = 4 THENSET nowYearLeaveDays = 16;ELSEIF elapseYear = 5 THENSET nowYearLeaveDays = 18;ELSEIF elapseYear >= 6 THENSET nowYearLeaveDays = 20;END IF;SET done = 0;SET p_员工号= empNo;UPDATE T_PAID_VACATIONSETLAST_YEAR_REMAIN_DAYS = lastYearRemainDays,THIS_YEAR_BASE_DAYS = nowYearLeaveDays,UPDATE_DATETIME = current_timestamp,UPDATE_USER_ID = 'SYS',UPDATE_TERMINAL_ID = 'MANUAL'WHERE EMP_NO = CONVERT(empNo USING binary);IF done = 3 THENRETURN 6;END IF;END LOOP;COMMIT;END4.MySql存储过程调用时的iBatis用Mapper例BaseInfoEditMapper.xml<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE mapperPUBLIC"-////DTD Mapper 3.0//EN""/dtd/ibatis-3-mapper.dtd"><mapper namespace="com.xxx.web.mapper.base_info_edit"><select id="VacationProcedure"parameterType="VacationBean"statementType="CALLABLE"> { call paid_vacation_compute (#{ReturnValue,javaType=INTEGER, jdbcType=INTEGER, mode=OUT},#{StaffNumber,javaType=String, jdbcType=CHAR, mode=INOUT},#{HireDate,javaType=String, jdbcType=VARCHAR, mode=IN},#{OperateID,javaType=String, jdbcType=VARCHAR, mode=IN})}</select></mapper>5.MySql函数调用时的iBatis用Mapper例BaseInfoEditMapper.xml<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE mapperPUBLIC"-////DTD Mapper 3.0//EN""/dtd/ibatis-3-mapper.dtd"><mapper namespace="com.xxx.web.mapper.base_info_edit"><select id="VacationProcedure"parameterType="VacationBean"statementType="CALLABLE"> { #{ReturnValue,javaType=INTEGER, jdbcType=INTEGER, mode=OUT} =call paid_vacation_compute (#{StaffNumber,javaType=String, jdbcType=CHAR, mode=IN},#{HireDate,javaType=String, jdbcType=VARCHAR, mode=IN},#{OperateID,javaType=String, jdbcType=VARCHAR, mode=IN} )} </select></mapper>6.JAVA调用例1(MySql存储过程和函数相同)package com.XXX.impl;import java.util.ArrayList;import java.util.List;import com.XXX.web.bean.VacationCreateBean;import com.XXX.web.dao.BaseInfoEditDAO;import com.XXX.web.util.BasicSqlSupport;public class BaseInfoEditDAOImpl extends BasicSqlSupport implements BaseInfoEditDAO { public boolean addBaseInfo(BaseInfoEditBean objUserInfo) throws Exception {boolean blnFlag=false;//成功FLAG;//全公司员工下一年度带薪休假一发赋予处理VacationCreateBean objVacationCreateBean = new VacationCreateBean();objVacationCreateBean.setStaffNumber(objUserInfo.getSTAFF_NUMBER());objVacationCreateBean.setHireDate(objUserInfo.getDATE_HIRE().toString());objVacationCreateBean.setOperateID(objUserInfo.getCREATE_USER_ID());objVacationCreateBean.setDhcWorkYearsShinKi(objUserInfo.getDHC_WORK_YEARS());String returnValue = (String)this.session.selectOne("com.XXX.web.mapper.base_info_edit.VacationProcedure", objVacationCreateBean);//System.out.println("staffNumber=" + objVacationCreateBean.getStaffNumber());//System.out.println("result=" + objVacationCreateBean.getReturnValue());//System.out.println("returnValue=" + returnValue);//追加結果の判断blnFlag=true;return blnFlag;}}7.処理DAO接口package com.XXX.web.dao;import java.util.List;import com.XXX.web.bean.BaseInfoEditBean;/*** 员工基本信息画面の処理DAO*/public interface BaseInfoEditDAO {public List<BaseInfoEditBean> selectAuthoriyList() throws Exception;public String selectStaffId() throws Exception;public int selectOpetateTimeNum(String strStaffNumber) throws Exception;public boolean addBaseInfo(BaseInfoEditBean objUserInfo) throws Exception;public boolean updateBaseInfo(BaseInfoEditBean objUserInfo) throws Exception;public BaseInfoEditBean searchBaseInfo(String strStaffNumber) throws Exception; }8.共同処理package com.XXX.web.util;import org.apache.ibatis.session.SqlSession;public class BasicSqlSupport{protected SqlSession session;public SqlSession getSession() {return session;}public void setSession(SqlSession session) {this.session = session;} }9. DAO与MAP间的交互BEANpackage com.XXX.web.bean;import java.io.Serializable;public class VacationCreateBean implements Serializable{private int ReturnValue;private String StaffNumber;private String HireDate;private String OperateID;private int WorkYearsShinKi;public int getReturnValue() {return ReturnValue;}public void setReturnValue(int returnValue) {ReturnValue = returnValue;}public String getStaffNumber() {return StaffNumber;}public void setStaffNumber(String staffNumber) {StaffNumber = staffNumber;}public String getHireDate() {return HireDate;}public void setHireDate(String hireDate) {HireDate = hireDate;}public String getOperateID() {return OperateID;}public void setOperateID(String operateID) {OperateID = operateID;}public int getDhcWorkYearsShinKi() {return dhcWorkYearsShinKi;}public void setDhcWorkYearsShinKi(int dhcWorkYearsShinKi) {this.dhcWorkYearsShinKi = dhcWorkYearsShinKi;}}10.通过MAIN函数进行调用package com.ohc.pms.batch;import java.io.FileInputStream;import java.io.IOException;import java.sql.CallableStatement;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.Properties;import org.apache.log4j.Logger;import org.apache.log4j.PropertyConfigurator;public class VacationCreate {/**JDBC驱动名 */static String jdbcDriver = "com.mysql.jdbc.Driver";/**DB URL */static String dbURL = "jdbc:mysql://172.999.999.35:3306/empdb";/** DB用户名 */static String user = "empuser";/**DB密码 */static String pass = "empuser123";/**日志输出 */static protected Logger log = Logger.getLogger(VacationCreate.class );public static void main(String[] args) {Connection conn = null;CallableStatement stmt = null;try{PropertyConfigurator.configure(System.getProperty("user.dir") + "\\" + "log4j.properties");("実行路径:" + System.getProperty("user.dir"));String fileName = "jdbc.properties"; // 属性文件名Properties conf = new Properties();try {conf.load(new FileInputStream(System.getProperty("user.dir") + "\\" + "jdbc.properties"));} catch (IOException e) {System.err.println("Cannot open " + fileName + ".");e.printStackTrace();System.exit(-1); // 程序終了}// 读入jdbcDriver = conf.getProperty("driver");dbURL = conf.getProperty("url");user = conf.getProperty("user");pass = conf.getProperty("password");//JDBC driver登録Class.forName("com.mysql.jdbc.Driver");("DB连接。