时间:2021-04-15 11:16:20 | 栏目:Mysql | 点击:次
使用存储过程,在操作数据库时开启事务,避免并发时同时操作造成数据重复
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetSerialNo`(IN tsCode VARCHAR(50),OUT result VARCHAR(200) ) BEGIN DECLARE tsValue VARCHAR(50); DECLARE tdToday VARCHAR(20); DECLARE nowdate VARCHAR(20); DECLARE tsQZ VARCHAR(50); DECLARE t_error INTEGER DEFAULT 0; DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET t_error=1; START TRANSACTION; /* UPDATE sys_sno SET sValue=sValue WHERE sCode=tsCode; */ SELECT sValue INTO tsValue FROM sys_sno WHERE sCode=tsCode; SELECT sQz INTO tsQZ FROM sys_sno WHERE sCode=tsCode ; -- 因子表中没有记录,插入初始值 IF tsValue IS NULL THEN SELECT CONCAT(DATE_FORMAT(NOW(),'%y%m'),'0001') INTO tsValue; UPDATE sys_sno SET sValue=tsValue WHERE sCode=tsCode ; SELECT CONCAT(tsQZ,tsValue) INTO result; ELSE SELECT SUBSTRING(tsValue,1,4) INTO tdToday; SELECT CONVERT(DATE_FORMAT(NOW(),'%y%m'),SIGNED) INTO nowdate; -- 判断年月是否需要更新 IF tdToday = nowdate THEN SET tsValue=CONVERT(tsValue,SIGNED) + 1; ELSE SELECT CONCAT(DATE_FORMAT(NOW(),'%y%m') ,'0001') INTO tsValue ; END IF; UPDATE sys_sno SET sValue =tsValue WHERE sCode=tsCode; SELECT CONCAT(tsQZ,tsValue) INTO result; END IF; IF t_error =1 THEN ROLLBACK; SET result = 'Error'; ELSE COMMIT; END IF; SELECT result ; END; dao Integer getFaultNo(Map<String, String> parameterMap);
xml
<update id="getFaultNo" parameterMap="getFaultMap" statementType="CALLABLE"> CALL GetSerialNo(?,?) </update> <!-- parameterMap.put("tsCode", 0); parameterMap.put("result", -1); --> <parameterMap type="java.util.Map" id="getFaultMap"> <parameter property="tsCode" mode="IN" jdbcType="VARCHAR"/> <parameter property="result" mode="OUT" jdbcType="VARCHAR"/> </parameterMap>
调用
Map<String, String> parameterMap = new HashMap<String, String>(); parameterMap.put("tsCode", "a"); parameterMap.put("result", "-1"); faultMapper.getFaultNo(parameterMap); // insert 故障日志 (主表) if (!parameterMap.get("result").equals("-1") && !parameterMap.get("result").equals("Error")) { //成功 } else { throw new RuntimeException(); }
总结