日期:2014-05-19  浏览次数:20593 次

使用HibernateTemplagte发生异常时事务没有回滚
Java code

@Transactional
public class Dao implements DaoIn{
    private HibernateTemplate template;
    public void save(Student s){
        try{
            template.save(s);
            throw new RuntimeException();
        } catch(RuntimeException e) {
            e.printStackTrace();
        } 
    }
    public HibernateTemplate getTemplate() {
        return template;
    }
    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }
}



Action
Java code

public class SpringAction extends ActionSupport{
    private Student stu = new Student();
    private DaoIn dao;
    public String execute()throws Exception{
        stu.setName("111");
        stu.setStuclassid(8);
        dao.save(stu);
        //this.wait();
        return SUCCESS;
    }//省略get,set



applicationContext.xml
XML code

<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

<bean id="SpringAction" class="test.web.SpringStruts2Hibernate.Action.SpringAction"
        scope="prototype">
        <property name="dao" ref="dao" />
    </bean>

    <bean id="dao" class="test.web.SpringStruts2Hibernate.DAOImpl.Dao">
        <property name="template" ref="hibernateTemplate" />
    </bean>
<!--省略数据源的配置信息-->



为什么throw new RuntimeException();
抛出异常后事务没有回滚,数据库中还是保存了数据了,是哪里少配置了什么吗?

------解决方案--------------------
注解的这种方式,没有用过,关注一下。
------解决方案--------------------
用hibernate模板的时候是不用捕获异常的
只有当你的操作抛出运行时异常的时候,spring才会帮你回滚
而你自己把异常给处理了,spring自然就不帮你忙了

hibernate模板的一大作用就是不用自己捕获异常并处理了
spring自己帮你处理了