mysql - Hibernate 不回滚触发器相关的更改

标签 mysql spring hibernate triggers transactions

我有一个带有 MySQL 数据库的应用程序。该数据库有一个表 A 和一个在该表中插入新行时的触发器。

现在,当我创建新实体(与此表相关联),并在事务中使用 session.save(aEntity); 保存它时,但是当我执行保存时,MySQL 激活了触发器表 A 并在其他表中创建一个新条目,但表 A 中的行直到我调用 transaction.commit() 时才会保存。

我有时需要回滚 transaction.rollback() 但触发器会在其他表中创建新条目并且不会被删除。

我该怎么做?

最佳答案

当您调用 save 时, Hibernate 将实体附加到持久性上下文,数据库行将在刷新期间添加。对于 MySQL,如果您使用 IDENTITY 实体标识符生成器,​​插入将立即发生。

触发器可能会在其他表中添加一条记录,但这也是当前数据库事务的一部分(假设您使用 InnoDB),因此当您回滚事务时,TableA 和其他表都不会保留挂起的更改。

所以你应该没问题。

更新

I'll try to explain. I have a table A and a table B. In MySQL, I have a trigger that when a row is created in A, the trigger creates a row in B with the same identifier of the row in A, (but without foreign key). In the Hibernate Session, I created a transaction and make an entity of A and save it. The trigger is activated and instantly creates an entry in B, but there is still no entry in A because I didn't commit the transaction yet. After I do a rollback, the table A is reverted but the row in B created by the trigger is still there, referencing an entry in A that does not exist. B does not have foreign keys and uses MyISAM.

这不是典型的数据库设置,也不是真正的 Hibernate 问题。您也会遇到普通 JDBC 的这个问题。问题在于表 A 使用事务感知的 InnoDB 存储引擎,而表 B 由于配置为使用 MyISAM 而在自动提交模式下工作。

关于mysql - Hibernate 不回滚触发器相关的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34745275/

相关文章:

php - 保存 SELECT 结果以便在另一个 SELECT 中重用

mysql - 使用从其他两个列和第二个表派生的列回显 MySQL 表

php - 如何使用数组 "echo"中的记录用于另一个 php select

php - 如何用 PDO::quote() 替换 mysql_escape_string

Java hibernate如何持久保存没有关系的实体列表?

java - 由于错误绑定(bind)扫描 <jar-file> 而创建 entityManagerFactory 时出错

spring - 使用 Spring-MVC 时如何查看来自客户端的 json?

java - 支持 JavaFX + Spring Boot + Hibernate 应用程序中的多种环境

java - 如何在hibernate中通过注解引入ondelete级联

mysql - 如何指示 hbm2ddl 为 MyISAM 引擎生成 sql