In this example, I don't know how to do rollback the transaction if a condition is verified. This is a Spring MVC application with JPA + Hibernate for persistence
In CartController:
@RequestMapping(value="/buy",method=RequestMethod.POST)
public String buy(){
CartDAO.buy();
return "redirect:/";
}//buy
In CartDAOImpl
@Transactional
public class CartDAOImpl implements CartDAO {
@PersistenceContext
private EntityManager em;
public void buy(){
....
if(x !=y) throw new MyException();
em.persist(Item);
....
}
}
In applicationContext-servlet.xml
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
What's the best solution to this problem? Sorry for my English
答案 0 :(得分:2)
From Spring documentation about rolling back declarative transactions:
In its default configuration, the Spring Framework’s transaction infrastructure code only marks a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException. ( Errors will also - by default - result in a rollback). Checked exceptions that are thrown from a transactional method do not result in rollback in the default configuration.
You can configure exactly which Exception types mark a transaction for rollback, including checked exceptions. The following XML snippet demonstrates how you configure rollback for a checked, application-specific Exception type.
答案 1 :(得分:1)
您可以在@Transactional
中声明希望Spring在您MyException
被抛出时执行回滚:
@Transactional(rollbackFor=MyException.class)