gpt4 book ai didi

mysql - WildFly 不保留 MySQL 中的存储过程调用

转载 作者:行者123 更新时间:2023-11-29 18:23:17 26 4
gpt4 key购买 nike

我正在开发一个在带有 MySQL 的 WildFly 8 上运行的 EJB 3 应用程序。我需要更新实体 (User) 内的计数器 (receiptCounter),并决定尝试使用存储过程调用来避免竞争条件。

这就是我创建存储过程的方式:

DELIMITER $$
CREATE PROCEDURE increment_receipt_counter
(
IN userID_in INT
)
BEGIN
UPDATE User SET receiptCounter = receiptCounter + 1 WHERE id = userID_in;
SELECT receiptCounter AS receiptCounter_new FROM User WHERE id = userID_in;
END
$$
DELIMITER ;

我是这样调用它的:

import javax.persistence.EntityManager;
import javax.persistence.StoredProcedureQuery;
...
public int incrementReceiptsCounter(int userID) throws InvalidEntityException, UnauthorizedException
{
StoredProcedureQuery q = entityManager.createStoredProcedureQuery("increment_receipt_counter");
q.registerStoredProcedureParameter("userID_in", Integer.class, ParameterMode.IN);
q.setParameter("userID_in", userID);
q.executeUpdate();
return (Integer)q.getSingleResult();
}

奇怪的是:当从 Java 调用时,该过程返回正确的新计数器值,但新值并未保留在数据库中。例如,如果在调用过程之前数据库中的receiptCounter为1,则Java中的过程调用返回2,但数据库中的用户表仍然显示值1。当我直接从MySQL命令行调用过程时,它工作得很好。我做错了什么?

最佳答案

在 mysql 命令行中,可以启用自动提交,这意味着您的更新会自动保留。

在java连接中,您可能禁用自动提交,因此更新不会提交,但selectupdate<在同一事务中运行,仍然返回更新后的值。

但是,如果您想处理并发,那么您应该首先使用 select ... for update 来锁定计数器,然后更新值。

关于mysql - WildFly 不保留 MySQL 中的存储过程调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46388990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com