我已成功将此注释用于Dao类。回滚适用于测试。
但是现在我需要回滚真实代码,而不仅仅是测试。有用于测试的特殊注释。但是哪些注释适用于非测试代码?对我来说这是一个大问题。我已经花了一天的时间。官方文档不符合我的需求。
class MyClass { // this does not make rollback! And record appears in DB. EmployeeDaoInterface employeeDao; public MyClass() { ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "HibernateDaoBeans.xml" }); employeeDao = (IEmployeeDao) context.getBean("employeeDao"); } @Transactional(rollbackFor={Exception.class}) public void doInsert( Employee newEmp ) throws Exception { employeeDao.insertEmployee(newEmp); throw new RuntimeException(); } }
employeeDao is
@Transactional public class EmployeeDao implements IEmployeeDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void insertEmployee(Employee emp) { sessionFactory.getCurrentSession().save(emp); } }
这是一个注释可以很好地运行的测试:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/HibernateDaoBeans.xml" }) @TransactionConfiguration(transactionManager = "txManager", defaultRollback = true) @Transactional public class EmployeeDaoTest { @Autowired EmployeeDaoInterface empDao; @Test public void insert_record() { ... assertTrue(empDao.insertEmployee(newEmp)); }
HibernateDaoBeans.xml
... <bean id="employeeDao" class="Hibernate.EmployeeDao"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="txManager"/> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> ...
是的,我回滚了交易。我刚刚为服务添加了BEAN …,然后注释@Transactional开始起作用:-)
<bean id="service" class="main.MyClass"> <property name="employeeDao" ref="employeeDao" /> </bean>
需RuntimeException从标记为的方法中抛出任何内容即可@Transactional。
RuntimeException
@Transactional
默认情况下,所有RuntimeExceptions都回滚事务,而检查的异常则不。这是EJB的遗留物。你可以使用rollbackFor()和noRollbackFor()注释参数进行配置:
RuntimeExceptions
rollbackFor()
noRollbackFor()
@Transactional(rollbackFor=Exception.class)
抛出任何异常后,这将回滚事务。