简体   繁体   中英

Spring Transaction or Hibernate Transaction

I am aware that I am posting a redundant question. I've gone through various posts in SO and other blogs too, but I've required bit more clarity on couple more items & so posting here.

I use Spring + Hibernate. I am inserting some 'n' records.

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();
}

Questions:

  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?

Though usage of transaction management varies from application to application, I can point out some important things as per my experience.

  1. Though both spring and hibernate provide transaction API, I would always go for Spring Declarative Transaction Management as it handles everything and I do not need to worry about rollback and commit.
  2. It is better to use session.getCurrentSession() which will return session for the current thread.
  3. If you are using Spring transaction management, rollback will be under spring managed transaction.

You do not need to use both Hibernate and Spring transaction.

Above points are based on my experience and may vary depending on the application requirement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM