【问题标题】:spring + hibernate: manually commit the transaction at endspring + hibernate:最后手动提交事务
【发布时间】:2013-03-31 13:09:33
【问题描述】:

我正在使用 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 和休眠

【问题讨论】:

    标签: java spring hibernate autocommit


    【解决方案1】:

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

    【讨论】:

    • 是的!这解决了我目前面临的问题。但你能告诉我,如果有什么方法可以不结合两种方法。实际上在休眠中我可以轻松地提交和回滚事务,但是在与 spring mvc 集成后,我遇到了问题。 ?
    • @ShahidGhafoor 你试过使用“@TransactionConfiguration(defaultRollback = false)”吗?我认为 Alexey 是对的,您可能需要将其分解为两种(或更多)方法。或者,您可以尝试使用 Spring 依赖注入获取您的 TransactionManager,或者通过手动提交/回滚实现您自己的 TransactionManager。但是,我个人并不是很喜欢这种选择。
    • @ShahidGhafoor,补充我之前的评论:static.springsource.org/spring/docs/3.0.x/…
    【解决方案2】:

    首先需要将属性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();
      }
    }
    

    【讨论】:

    • 异常:没有 Hibernate Session 绑定到线程,并且配置不允许在这里创建非事务性会话,因为我使用的是 Spring + Hibernate
    猜你喜欢
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 2015-11-09
    • 2015-12-17
    相关资源
    最近更新 更多