日期:2014-05-18 浏览次数:20805 次
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
public static final String DisallowedMessage = "Hello, hack";
//使用声明式事务
@Transactional
public void save(Message message){
long msgId = (Long)sessionFactory.getCurrentSession().save(message);
System.out.println("generate message id:" + msgId);
//为了测试事务, 在保存后,再检查消息
if(DisallowedMessage.equals(message.getText())){
throw new RuntimeException("reject a bad message.");
}
}
@Test
public void testSaveWithRollback(){
String text = "Hello Batman";
try{
//正常消息
Message message = new Message(text);
messageService.save(message);
//异常消息
message = new Message(MessageService.DisallowedMessage);
messageService.save(message);
fail("Not rollback when occuring RuntimeException!");
}catch (Exception rex){
}
List messaes = messageService.findAllMessages();
for(Iterator iter = messaes.iterator(); iter.hasNext();){