我遇到了Spring回滚事务的问题。我有一个方法,可以在几个表中创建一个新订单(users
,order
,order_product
...)。如果在方法完成之前存在异常,则启动回滚并删除order_product
中的记录,但仍保留users
记录。我想删除我的数据库中生成的所有记录。 users id
字段(主键)由MySQL 5.6中的Autoincrement生成。并且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
}
}
答案 0 :(得分:0)
在此处,您将在每个@Transactional
方法执行每个数据库插入/更新步骤。此批注在该方法的执行开始时创建Db事务会话,并在方法执行结束时提交。
这里,每个db插入都在不同的数据库会话中。如果要在发生运行时异常时回滚所有db更新,则所有这些事务应位于同一会话中。但这不是。这是导致问题的原因。
您可以做的是,将所有这些代码放在一个用@Transactional
注释的方法中
我会建议一种模式..
@Repository
注释该类。@Service
注释的类作为@Transactional
注释的方法。因此,每种方法都将在 SAME跨国会话中。现在,您可以使用相同的服务方法调用许多DAO方法。如果这些DAO方法中的任何一个具有运行时异常,则所有内容都将回滚。 摘要:在执行@Transactional
的单个方法期间放置所有数据库查询,以便在发生运行时异常时自动回滚。
注意:您可以设置@Transactional
,方法级别或班级
答案 1 :(得分:0)
@Service
@Transactional(rollbackFor = Exception.class)

使用上面的注释来回滚任何异常