我在使用 Spring 共享 EntityManager
的方法上有一个 @Transactional(rollbackFor=Exception.class)
注释。但是当我有意将用户名设置为重复时,事务不会回滚持久调用。原始的唯一用户名仍然提交给数据库。持久调用的行为就像它有自己的提交规则一样。在 Debug模式下执行此行后,我可以立即在 mysql 控制台中选择此值。这可能意味着它是自动提交的。 SQL 日志记录在行执行时显示插入语句,而在回滚发生时没有删除语句。回滚在内存数据库中的 H2 中完全按预期工作。
- 我有
spring.jpa.open-in-view=false
- 我尝试使用
em.find
修改一个值,然后抛出异常。修改被正确回滚。所以只有持久调用才是问题 - 我尝试了传播
REQUIRE
REQUIRE_NEW
但没有用 用于连接的数据库用户有适当的权限
@PersistenceContext EntityManager em; @Transactional(rollbackFor = Exception.class) public User save(User user) { em.persist(user); user.setUsername("duplicate"); // this will throw an exception upon flushing the change return user; }
如何停止此行为并使持久调用与其他所有内容一起提交?
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
更新: 手动抛出 new Exception 或调用 em.flush() with integrity violation 也不会导致回滚。回滚发生但不删除插入的记录。
2018-10-23 00:26:36.909 DEBUG 5475 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager : Initiating transaction rollback
2018-10-23 00:26:36.913 DEBUG 5475 --- [nio-8080-exec-1] o.s.orm.jpa.JpaTransactionManager : Rolling back JPA transaction on EntityManager [SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.crawlers.main.models.User#85]],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])]
Annotation @Transactional. How to rollback? 没有解决方案为我工作。尝试了所有解决方案和评论:(
最佳答案
已解决。见评论。我的表由 MyISAM 支持,它不支持回滚。每个查询单独运行,持久调用立即提交。
关于java - JPA 事务未回滚持久调用。仅在 MySQL 上插入和提交忽略事务规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52938032/