我成功地将这个注释用于 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();
}
}
杜员工
@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));
}
HibernateDougBeans.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>
谢谢大家,俄罗斯不会忘记你们的!