事务在异常后没有回滚

时间:2015-12-09 00:07:36

标签: hibernate spring-mvc jpa

我正在运行jpa / spring-mvc项目并在此代码中:

@Autowired
private GenericDao<AoModification, Integer> modif_dao;
....
@Transactional
public void save_ao( ... ) 
        throws ParseException, UnsupportedEncodingException {

    modif_dao.delete(ao.getAoModifications());

    modif_dao.create(new AoModification(
       new SimpleDateFormat("dd/MM/yyyy").parse(mf.date), mf.txt));
    ....

我得到了java.text.ParseException: Unparseable date: "06-10-2011"而且我忘了放new SimpleDateFormat("dd-MM-yyyy").parse(mf.date)

问题是,即使异常抬高,此行modif_dao.delete(ao.getAoModifications());已在数据库中保留,并且事务没有回滚,我丢失了所有AoModifications

问题出在哪里!!!

@Repository注释是使用@Transactional自动创建方法吗?

hibernate.xml

<context:component-scan base-package="service"/>
<context:component-scan base-package="dao"/>

<tx:annotation-driven transaction-manager="transactionManager" />

dao.GenericDaoJpaImpl.java

@Repository
public class GenericDaoJpaImpl<T, PK extends Serializable> 
                                            implements GenericDao<T, PK> {

    @PersistenceContext
    protected EntityManager entityManager;

    ....

    @Override
    public void delete(T t) {
        this.entityManager.remove(this.entityManager.contains(t) ? t : this.entityManager.merge(t));
    }

    @Override
    public void delete(Set<T> ts) {
        for( T t : ts){
            delete(t);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

它不会回滚,因为java.text.ParseException是从java.lang.Exception继承的,而不是来自java.lang.RuntimeException。默认情况下,当发生RuntimeException时,会回滚带有@Transactional注释的方法。

您可以捕获ParseException(或Exception)并重新抛出RuntimeException,例如:

@Transactional
public void save_ao( ... ) {

    try {
        modif_dao.delete(ao.getAoModifications());

        modif_dao.create(new AoModification(
            new SimpleDateFormat("dd/MM/yyyy").parse(mf.date), mf.txt));
        ....
    } catch (Exception e) {
        throw new RuntimeException("Error when saving ao...", e);

    }

或者您可以修改@Transactional注释以使用rollbackFor选项回滚Exception:

@Transactional(rollbackFor=Exception.class)