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

Hibernate does not rollback trigger-related changes

我有一个带有 MySQL 数据库的应用程序。当在此 table.

中插入新行时,此数据库有一个 table A 和一个触发器

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

时才会保存

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

我该怎么做?

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

触发器可能会在其他 table 中添加一条记录,但这也是当前数据库事务的一部分(假设您使用 InnoDB),因此当您回滚事务时,Table A 或其他 table 将保留未决更改。

所以你应该没问题。

更新

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 遇到这个问题。问题是 Table A 使用 transaction-aware InnoDB 存储引擎,而 Table B 在 auto-commit 模式下工作,因为配置为使用 MyISAM。