spring + hibernate:最后手动提交事务

时间:2013-03-31 13:09:33

标签: java spring hibernate autocommit

我正在使用spring mvc和hibernate

@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和hibernate

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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();
  }
}