Pergunta

I'm trying to use generic-dao (http://code.google.com/p/hibernate-generic-dao/ ). However, in my HibernateBaseDAO the getSession() method is implemented as sessionFactory.getCurrentSession(). This leads to an error for any entity update

org.hibernate.HibernateException: createCriteria is not valid without active transaction

However, when I use openSession() in place of getCurrentSession(), it works. I'm not using spring as a dependency in pom.xml. I've been reading on openSession() and getCurrentSession(), however still can't understand why this is happening?

Foi útil?

Solução

Found the solution, with genericDAO it gets the current session which needs to be explicitly open using openSession(), while getCurrentSession() just attaches it to the current session. According to the author

GenericDAO makes the assumption that you will be handling transactions externally to the DAO

Outras dicas

The currentSession turns out in many situations to be very fragile.

You may have undefined state after an error, so please make sure that your "current session" and transaction was not destroyed by a previous error. to achive this, print out the transaction state (isActive) just before using calling getCurrentSession inside the DAO.

Double-check that the SessionContext is configured and working; call getCurrentSession twice and check if returned instances are same, if not, you may are looking at different sessions:

assert getCurrentSession()==getCurrentSession()

I learned hard lessons to be very conservative with Hibernate. So spending some time on basics really pays off.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top