Вопрос

I am using spring mvc and 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";
    }



}

How I commit the transaction manually as all the transactions save successfully, if any transaction fails to insert , rollback all the transactions in catch block. ?

I am using spring mvc and hibernate

Это было полезно?

Решение

I would prefer to create a separate method (combining your 2 methods) in some service to handle all necessary transactions there.

Другие советы

First the property connection.autocommit needs to be set to false, to enable transaction level commit.

This can be done by adding

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

in hibernate.cfg.xml

secondly, use the following kind of code at your DAO level

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();
  }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top