使用存储过程,在操作数据库时开启事务,避免并发时同时操作造成数据重复
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
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
1
2
3
4
5
6
7
8
9
10
11
|
< 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> |
调用
1
2
3
4
5
6
7
8
9
10
11
|
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(); } |
总结
以上所述是小编给大家介绍的mybatis+mysql 使用存储过程生成流水号的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://www.jianshu.com/p/d7570564f104