我遇到了Spring回滚事务的问题。我有一个方法,它在几个表(users、order、order_product.)中创建一个新的插入顺序。如果在方法完成之前出现异常,则启动回滚,删除order_product中的记录,但users记录仍然保留。我想删除在我的数据库中生成的所有记录。users id字段(主键)是由MySQL 5.6中的自动增量生成的。order_product的主键是两个外键。
用户表:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`email` varchar(255) NOT NULL,
`new_email` varchar(255) DEFAULT NULL,
`allowed_newsletter` bit(1) NOT NULL DEFAULT b'1',
`lastname` varchar(255) DEFAULT NULL,
`phone` varchar(255) DEFAULT NULL,
`lang` enum('en','de','fr','es') DEFAULT 'es',
`creation_date` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `IDX_EMAIL` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1092 DEFAULT CHARSET=latin1;order_product表:
CREATE TABLE `order_product` (
`product_id` int(11) NOT NULL,
`order_id` int(11) NOT NULL,
`detail_json` longtext,
`shipping_date` datetime DEFAULT NULL,
`order_product_status` enum('PaymentPending','ShippingPending','Sent','Cancelled') NOT NULL DEFAULT 'PaymentPending',
`is_downloaded` bit(1) NOT NULL DEFAULT b'0',
PRIMARY KEY (`product_id`,`order_id`),
KEY `IDX_OP_PRODUCT_ID` (`product_id`) USING BTREE,
KEY `IDX_OP_ORDER_ID` (`order_id`) USING BTREE,
CONSTRAINT `FK_OP_ORDER_ID` FOREIGN KEY (`order_id`) REFERENCES `order_customer` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_OP_PRODUCT_ID` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8我正在使用MySQL 5.6、Hibernate 4和Spring 4。
与日志文件相关的:
[annotation.AnnotationTransactionAttributeSource(getTransactionAttribute:108)] Adding transactional method 'UsersDAOImpl.insertUser' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT;
[jpa.JpaTransactionManager(doGetTransaction:334)] Found thread-bound EntityManager [org.hibernate.ejb.EntityManagerImpl@395dbec7] for JPA transaction
[jpa.JpaTransactionManager(handleExistingTransaction:476)] Participating in existing transaction
[spi.ActionQueue(addResolvedEntityInsertAction:213)] Executing identity-insert immediately
[hibernate.SQL(logStatement:104)]
insert
into
users
(allowed_newsletter, email, lang, lastname, name, new_email, phone)
values
(?, ?, ?, ?, ?, ?, ?)
2016-12-19 09:47:46,046 DEBUG (http-bio-8080-exec-3) [id.IdentifierGeneratorHelper(getGeneratedIdentity:93)] Natively generated identity: 1091
2016-12-19 09:47:46,047 DEBUG (http-bio-8080-exec-3) [spi.ActionQueue(addResolvedEntityInsertAction:213)] Executing identity-insert immediately
.....
... MORE INSERTs - SELECTs - etc ...
.....
[annotation.AnnotationTransactionAttributeSource(getTransactionAttribute:108)] Adding transactional method 'OrderProductServiceImpl.addNewOrderProduct' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
[jpa.JpaTransactionManager(doGetTransaction:334)] Found thread-bound EntityManager [org.hibernate.ejb.EntityManagerImpl@395dbec7] for JPA transaction
[jpa.JpaTransactionManager(handleExistingTransaction:476)] Participating in existing transaction
[annotation.AnnotationTransactionAttributeSource(getTransactionAttribute:108)] Adding transactional method 'OrderProductDAOImpl.addNewOrderProduct' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
[jpa.JpaTransactionManager(doGetTransaction:334)] Found thread-bound EntityManager [org.hibernate.ejb.EntityManagerImpl@395dbec7] for JPA transaction
[jpa.JpaTransactionManager(handleExistingTransaction:476)] Participating in existing transaction
[internal.AbstractSaveEventListener(saveWithGeneratedId:130)] Generated identifier: component[orderId,productId]{orderId=144, productId=2553}, using strategy: org.hibernate.id.CompositeNestedGeneratedValueGenerator
[writers.HstsHeaderWriter(writeHeaders:130)] Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@1d011fbb
[context.HttpSessionSecurityContextRepository(saveContext:352)] SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
[internal.SessionImpl(disconnect:566)] Disconnecting session
[internal.LogicalConnectionImpl(releaseConnection:232)] Releasing JDBC connection
[internal.LogicalConnectionImpl(releaseConnection:250)] Released JDBC connection
[jpa.JpaTransactionManager(processRollback:851)] Initiating transaction rollback
[jpa.JpaTransactionManager(doRollback:538)] Rolling back JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@395dbec7]
[spi.AbstractTransactionImpl(rollback:203)] rolling back
[jdbc.JdbcTransaction(doRollback:164)] rolled JDBC Connection
[jdbc.JdbcTransaction(releaseManagedConnection:126)] re-enabling autocommit
[internal.JdbcCoordinatorImpl(close:173)] HHH000420: Closing un-released batch
[jpa.JpaTransactionManager(doCleanupAfterCompletion:600)] Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@395dbec7] after transaction
[jpa.EntityManagerFactoryUtils(closeEntityManager:435)] Closing JPA EntityManager
[internal.LogicalConnectionImpl(releaseConnection:232)] Releasing JDBC connection
[internal.LogicalConnectionImpl(releaseConnection:250)] Released JDBC connection编辑:
@Controller
public class OrderController {
@ResponseStatus(value = HttpStatus.ACCEPTED)
@Transactional
public void finishPayment(...) {
//Call to service methods
}
}
@Service
@Transactional
public class UsersServiceImpl implements UsersService {
public UsersEntity registerNewGuest(String username, String email, MCountryEntity countryEntity, String nickname, String lang) {
// Insert User
}
}
@Service
@Transactional
public class OrderProductServiceImpl implements OrderProductService {
@Override
public void addNewOrderProduct(OrderProductEntity orderProductEntity) {
// Insert OrderProduct
}
}发布于 2016-12-19 10:16:12
在这里,您将在每个@Transactional方法上执行每个db插入/更新步骤。该注释在执行该方法时创建一个Db事务会话,并在方法执行结束时提交。
在这里,每个db insert位于不同的数据库会话中。如果您想在运行时异常发生时回滚所有db更新,那么所有这些事务都应该在同一个会话中。但这里没有。这就是你问题的原因。
您可以做的是,将所有这些代码放入一个带有@Transactional注释的方法中。
我会建议一个模式..。
@Repository对该类进行注释。@Service注释的方法,请使用带有@Transactional注释的类。因此,这些方法中的每一种都将在中相同的跨国会话中。现在您可以在同一个服务方法中调用许多DAO方法。如果这些DAO方法中有任何一个有运行时异常,那么所有内容都会回滚。汇总:在使用@Transactional执行单个方法期间,如果出现运行时异常,则将所有db查询自动回滚。
注意事项:您可以将@Transactional、方法级别或类级别放在
发布于 2016-12-19 11:15:32
@Service
@Transactional(rollbackFor = Exception.class)
使用上面的注释对任何异常回滚
https://stackoverflow.com/questions/41219191
复制相似问题