首先,我制作了一个MYSQL过程来增加一个数字[每次] +1(其中没有交易),然后在Spring Transaction中调用n(n> 1)次该过程并得到一个相同的数字,最后数字+1(预期为+ n)
其次,我在过程中添加了TRANSACTION并提交atfer +1,得到的结果与上述相同;
第三,我在方法A上添加了@Transaction(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)(A调用过程),并在方法B中多次调用方法A,并用@Transactional进行注解,然后我得到了与上述相同的结果;
有人帮忙吗?你能给我一种处理方法吗?
加: MySQL中的表
CREATE TABLE `SEQUENCE` (
`ID` bigint(10) NOT NULL ,
`COUNT` int(11) NOT NULL ,
`CUR_DATE` date NOT NULL ,
`READ_ME` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
PRIMARY KEY (`ID`)
);
MySQL中的过程
CREATE DEFINER="root"@"%" PROCEDURE "SEQUENCE_PROCEDURE"(IN _id bigint)
BEGIN
UPDATE `SEQUENCE` SET `COUNT`=-1,CUR_DATE=now() where `ID`=_id and TIMESTAMPDIFF(DAY,CUR_DATE,now())>0 and _id=1;
UPDATE `SEQUENCE` SET `COUNT`=-1,CUR_DATE=now() where `ID`=_id and TIMESTAMPDIFF(MONTH,CUR_DATE,now())>0 and _id=2;
UPDATE `SEQUENCE` SET `COUNT`=`COUNT`+1 where `ID`=_id;
SELECT * FROM `SEQUENCE` where `ID`=_id;
END
mybatis中的SQL
<select id="getSequence" parameterType="java.lang.Long" resultMap="baseResult" statementType="CALLABLE">
{call SEQUENCE_PROCEDURE(#{id,jdbcType=BIGINT,mode=IN})}
</select>
项目中的测试
@Test
@Transactional
public void testSequence() {
System.out.println(sequenceService.getId(2L));
System.out.println(sequenceService.getId(2L));
System.out.println(sequenceService.getId(2L));
}
其中
public String getId(Long id) {
Sequence sequence = sequenceMapper.getSequence(id);
String temp='000000000000'+sequence.getCount();
return temp.substring(temp.length-12);
}
测试结果
000000000000 000000000000 000000000000
预期结果
000000000000 000000000001 000000000002
在过程中添加START TRANSACTION和COMMIT无效!
答案 0 :(得分:0)
在您的过程中,第1行和第2行对id 1和2有特定的查询(为什么?),并对_id
变量进行双重比较。另外,第三个查询在另一个表COUNT
上运行,可能是错误。
我假设记录已经存在,就更改了过程,并将第三个查询更改为SEQUENCE
表:
CREATE PROCEDURE SEQUENCE_PROCEDURE(IN _id bigint)
BEGIN
UPDATE `SEQUENCE` SET `COUNT`=-1,CUR_DATE=now()
WHERE `ID`=_id and TIMESTAMPDIFF(DAY,CUR_DATE,now())>0;
UPDATE `SEQUENCE` SET `COUNT`=`COUNT`+1 where `ID`=_id;
SELECT * FROM `SEQUENCE` where `ID`=_id;
END