I'm having trouble with my HibernateTemplate derived class - it isn't committing transactions. The data changes appear to have been made until I restart my application server, but when I do that, they are gone. I'm pretty sure that the problem is that transactions are not being committed - but I was under the impression that HibernateTemplate took care if that sort of thing for you.
I set up my template as so:
My first cut Java looked like this:Code:<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean"> <property name="mappingDirectoryLocations"> <list> <value>classpath:/uk/co/foobar/morph/dto</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">net.sf.hibernate.dialect.DB2400Dialect</prop> <!-- etc... --> </props> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate.HibernateTemplate"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <!-- Hibernate data transfer objects --> <bean class="uk.co.foobar.morph.dao.CompanyHibernateDAO" id="companyDAO"> <property name="hibernateTemplate"> <ref bean="hibernateTemplate"/> </property> </bean>
As I said, this isn't committing. My next try was:Code:public class CompanyHibernateDAO extends HibernateDaoSupport implements CompanyDAO { public void saveCompany(final Company company) throws DAOException { this.logger.debug("Saving company " + String.valueOf(company)); getHibernateTemplate().save(company); } }
This seems to work fine. Unfortunately, getSession()'s JavaDoc specifically warns you off using it from HibernateTemplate. It advises you to use a HibernateCallback, which gives you a connection, so I tried:Code:public void saveCompany(final Company company) throws DAOException { this.logger.debug("Saving company " + String.valueOf(company)); getHibernateTemplate().save(company); getSession().connection().commit(); }
This doesn't commit. :-(Code:public void saveCompany(final Company company) throws DAOException { this.logger.debug("Saving company " + String.valueOf(company)); getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { session.save(company); session.connection().commit(); return null; } }); }
I also looked at HibernateTransactionManager, but I didn't see any way of using this with HibernateTemplate. It appears to be needed for more complex situations that mine, where you need more control over transactions, and don't use HibernateTemplate.
BTW, I will need real transactions at some point, so I don't want to just use auto-commit and flush().
What am I doing wrong? Is there a way of getting HibernateTemplate's convenience methods to commit transactions? If not, what are they for - and what should I do instead?


Reply With Quote