Spring 事务或 Hibernate 事务

Spring Transaction or Hibernate Transaction

我知道我发布了一个多余的问题。我也浏览了 SO 和其他博客中的各种帖子,但我需要更清楚地了解更多的项目,所以在这里发布。

我使用 Spring + Hibernate。我正在插入一些 'n' 条记录。

MySpringController.java

@Transactional
@RequestMapping(...)
public String saveRecords(@ModelAttribute("orderObj") Order order){
  for(Item item : order.getItems()){
    itemDAO.save(item);
  }
  return "saveSuccess";
}

MyHibernateDAO class

public void save(Item item){
  session = sf.openSession();
  Transaction tx = session.beginTransaction();
  session.persist(item);
  tx.commit();
  session.close();
}

问题:

  1. There are Transaction enabled in both Spring and Hibernate. Is this good practice to do so? Or transaction in either component is sufficient?

  2. During such bulk transaction, which is advisable to use session.openSession() or session.getCurrentSession()? Is it good practice to open & close transaction every time during a bulk submit?

  3. Now if rollback happens, under which scope it would be? under Hibernate's or Spring's transaction?

虽然事务管理的使用因应用程序而异,但我可以根据我的经验指出一些重要的事情。

  1. 虽然 spring 和 hibernate 都提供事务 API,但我总是会选择 Spring 声明式事务管理,因为它处理所有事情,我不需要担心回滚和提交.
  2. 最好使用 session.getCurrentSession(),它将 return 当前线程的会话。
  3. 如果您正在使用 Spring 事务管理,回滚将在 spring 管理的事务下进行。

您不需要同时使用 Hibernate 和 Spring 事务。

以上几点是根据我的经验得出的,可能会因应用要求而异。