Hibernate 交易没有发生';出现异常后无法回滚
我正在运行一个Hibernate 交易没有发生';出现异常后无法回滚,hibernate,spring-mvc,jpa,Hibernate,Spring Mvc,Jpa,我正在运行一个jpa/springmvc项目,在此代码中: @Autowired private GenericDao<AoModification, Integer> modif_dao; .... @Transactional public void save_ao( ... ) throws ParseException, UnsupportedEncodingException { modif_dao.delete(ao.getAoModifica
jpa
/springmvc
项目,在此代码中:
@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));
....
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);
}
}
}
@存储库
公共类GenericDaoJpaImpl
实现GenericDao{
@持久上下文
受保护的实体管理器实体管理器;
....
@凌驾
公共作废删除(T){
remove(this.entityManager.contains(t)?t:this.entityManager.merge(t));
}
@凌驾
公共作废删除(集合ts){
for(T:ts){
删除(t);
}
}
}
它不会回滚,因为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);
}
或者,您可以使用rollbackFor选项修改@Transactional annotation以回滚异常:
@Transactional(rollbackFor=Exception.class)
谢谢,我现在明白了;)你能举个例子说明如何捕获ParseException(或Exception)并重新抛出RuntimeException,这样你的答案就完美了。我添加了一个例子,所以现在应该很清楚我的意思。谢谢,我选择使用
@Transactional(rollboor=Exception.class)
@Transactional(rollbackFor=Exception.class)