我在我的应用程序中使用 OpenSessionInView。我的目标是在发生任何异常时以一种方法回滚数据库中的所有更改。这是我的控制器:
@RequestMapping(value="/kartazadan.do", method=RequestMethod.GET )
@Transactional(rollbackFor=Exception.class)
public ModelAndView viewGET(HttpServletRequest request,
HttpServletResponse response) throws Exception{
int id = Integer.parseInt(ServletRequestUtils.getRequiredStringParameter(request, "id"));
ModelMap modelMap = new ModelMap();
KartaZadan kartaZadan = kartaZadanDAO.getkartaZadanById(id);
kartaZadan.setZadanie("TEST10");
kartaZadanDAO.update(kartaZadan);
kartaZadan = kartaZadanDAO.getkartaZadanById(null); //here when Exception should occurr and make transaction rollback
kartaZadanDAO.update(kartaZadan);
modelMap.addAttribute("kartaZadan", kartaZadan);
setCommonFields(modelMap);
modelMap.addAttribute("errorsEnabled", false);
return new ModelAndView("kartaZadan", modelMap);
}
使用下面给出的配置,它可以工作:在 web.xml 中:
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<bean class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
但是在这种策略中,我无法保存/更新视图中的任何行。所以我像这样覆盖了 OpenSessionInViewFilter:
public class CustomOpenSessionInViewFilter extends OpenSessionInViewFilter{
@Override
public void closeSession(Session session, SessionFactory sessionFactory){
session.flush();
super.closeSession(session,sessionFactory);
}
}
现在我可以保存/更新,但事务不回滚......如何让它们同时工作?