你可以把这两个操作写在一个Service中,一般一个Action方法中除了使用get/load以外,应该只操作一个Service, 否则就是两个事务了.要不你也可以自己写一个反射的Action类,每次调用Action自动打开一个和数据库的会话,里面怎么操作不管,当Action返回之后再commit,就可以保证事务的一致性了.比如我用的是Struts + Hibernate,在Action中的execute中写:public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; String methodStr = mapping.getParameter(); // 根据parameter名字的不同, 调用不同的方法 Class[] types = new Class[] { ActionMapping.class, ActionForm.class, HttpServletRequest.class, HttpServletResponse.class, Session.class}; Session session = null; // 声明会话 try {session = HibernateSessionFactory.getSession();session.beginTransaction();Object[] params = new Object[] { mapping, form, request, response, session }; // 向Action方法中传递和数据库的会话, 这个会话可以保证事务的完整性Method method = this.getClass().getMethod(methodStr, types);if (method != null) { forward = (ActionForward) method.invoke(this, params); session.getTransaction().commit(); // 执行成功, 则提交} } catch (Exception e) {e.printStackTrace();session.getTransaction().rollback(); // 出现错误就全部回滚 } return forward;}这样Action只要继承这个类, 就可以在自己的方法中获得到一个Session, 用这个session怎么操作数据库, 都可以保证事务的完整性了. |