Benefits of using Springs Transaction management vs using hibernate

前端 未结 2 1532
小鲜肉
小鲜肉 2021-02-01 06:59

I\'ve been trying to learn spring and hibernate, and I\'ve used a lot of examples around the net to put together a nice application. However, I realized now that Spring supports

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-01 07:55

    The real advantages are:

    • Lightweight declarative syntax. Compare:

      public void saveEmployee(Employee e) {
          Session s = sf.getCurrentSession();    
          s.getTransaction().begin();
          s.save(e);    
          s.getTransaction().commit();
      }
      

      and

      @Transactional
      public void saveEmployee(Employee e) {
          sf.getCurrentSession().save(e);
      }
      
    • Flexible transaction propagation. Imagine that now you need to execute this saveEmployee() method as a part of a complex transaction. With manual transaction management, you need to change the method since transaction management is hard-coded. With Spring, transaction propagation works smoothly:

      @Transactional
      public void hireEmployee(Employee e) {
          dao.saveEmployee(e);
          doOtherStuffInTheSameTransaction(e);
      }
      
    • Automatic rollback in the case of exceptions

提交回复
热议问题