0

我正在使用 spring mvc 和休眠

@Controller
public class COACategoriesController {

protected static Logger log = Logger.getLogger(COACategoriesController.class);


@Resource(name="COACategoriesService")
private COACategoriesService obj_coacs;
@Resource(name="COAMaintenanceService")
private COAMaintenanceService obj_coams;

 @RequestMapping(value = "/addCoaCategory", method = RequestMethod.POST)
 public String addCoaCategory(@RequestParam("conCatName") String coaCatName, Model model) {

     Date sysdate = null;
     String Message="";
     try{

     sysdate = new Date();


     COACategoriesModel model1 = new COACategoriesModel( coaCatName, 1, "", sysdate , 0);

     COAMaintenanceModel account =  new COAMaintenanceModel();
        account.setDiscription("Test Description");
        account.setCategoryId(model1);

        Message="Fail-First";
        obj_coacs.AddCOACategories(model1);


        Message="Fail-Second";
        obj_coams.AddCOAMaintenance (account);


        Message="Add Successfully";
     }catch(Exception ex){
         log.error("Exception.."+ex);
         model.addAttribute("success", Message);
     }



        return "fin/category";
    }



}

当所有事务成功保存时,我如何手动提交事务,如果任何事务插入失败,则回滚 catch 块中的所有事务。?

我正在使用 spring mvc 和休眠

4

2 回答 2

3

我宁愿在某些服务中创建一个单独的方法(结合您的 2 种方法)来处理那里的所有必要事务。

于 2013-03-31T13:28:18.893 回答
1

首先connection.autocommit需要将属性设置为false,以启用事务级提交。

这可以通过添加来完成

<property name="connection.autocommit">false</property>

hibernate.cfg.xml

其次,在您的 DAO 级别使用以下类型的代码

Session s = null;
Transaction t = null;
try {
  s = getSessionFactory().openSession();
  t = s.beginTransaction();
  // code to persist the object

}
catch(HibernateException he) {
  if(t != null) {
     t.rollback();
  }
}
finally {
  if(s != null) {
    s.close();
  }
}
于 2013-03-31T13:33:43.563 回答