views:

814

answers:

1

I have next working code:

 Session session = null;

 try {

  SessionFactory sessionFactory = new Configuration().configure()
    .buildSessionFactory();
  session = sessionFactory.openSession();

  String id = (String) FacesContext.getCurrentInstance()
    .getExternalContext().getRequestParameterMap().get(
      "storeId");

  Transaction t = session.beginTransaction();

  stores = getStores();

  for (Store store : stores) {
   if (store.getId() == Integer.parseInt(id)) {
    session.delete(store);
   }
  }
  t.commit();
 } catch (Exception e) {
 } finally {
  session.close();
 }
}

When i try redo this code to use Hibernate template, i go unending request to DB:

    HibernateTemplate template = new HibernateTemplate();
    template .setSessionFactory(sessionFactory);

    stores = template.find("from Stores");

    for (Store store : stores) {
      if (store.getId() == Integer.parseInt(id)) {
        template.delete(store);
}}

Looks like transaction is not closed.

How could I close transaction this case? And is it will better at all to use Hibernate template approach instead of session approach showed at first code?

+3  A: 

You didn't say it, but I assume you're referring to the HibernateTemplate class in the Spring Framework. HibernateTemplate participates in Spring transactions, but it doesn't manage them on its own. Spring provides a lot of ways to manage transactions both programmatically and declaratively. If you're just experimenting, you can use the TransactionTemplate class to quickly test it out. For larger projects, you should consider using declarative transaction management because it simplifies your code, although it's a little trickier to set up initially.

As for whether or not the HibernateTemplate approach is better than managing your sessions manually, I'd say anything that reduces boilerplate code is a good thing, so yes. This is especially crucial on big projects. However, depending on your project, HibernateTemplate might not even be necessary. It was originally created to work around some deficiencies in Hibernate 2.x, but many of those deficiencies were eliminated in Hibernate 3. So before adopting it, read the HibernateTemplate JavaDoc for a discussion of the advantages.

Rob H
Rob,thank you for answer, this area is more clear for me now.Yes, you are right, I mentioned HibernateTemplate class in the Spring Framework.
sergionni
+1. And if you do end up using HibernateTemplate, have Spring inject it into your DAOs instead of manually creating it. You can do that directly or by extending HiberanteDaoSupport.
ChssPly76