We are upgrading an app from Hibernate 5.6 and Spring 5.3. The biggest change for us seems to be the sessionFactory session management. With the old libraries, we could inject our SessionFactory into all services and use sessionFactory.getCurrentSession() to do all of our persistence. Accessing any code in our @Transactional services would open a session and start a transaction.
After upgrading libraries to spring 6.2 and hibernate 6.6, the SessionFactory/EntityManager does not have an open session anymore. If we inject with @PersistenceContext then the session is open.
// old way does not have open session
@Resource(name = "sessionFactory")
protected SessionFactory m_sessionFactory;
// new way has open session
@PersistenceContext
protected Session session;
Injecting the EntityManager and EntityManagerFactory behave the same way. I have read and searched all the spring and hibernate docs and examples I could find, and still can't find where this behavior was documented to have change.
My question now is, does anyone know how to explain how it worked before? And is there a way that we can get it to work that way again?
<bean id="sessionFactory"
class=".springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="JPATest" />
<property name="persistenceXmlLocation" value="classpath:persistence.xml" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="vendorAdapter" />
<property name="jpaDialect">
<bean class=".springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<persistence xmlns=";
xmlns:xsi=";
xsi:schemaLocation=";>
<persistence-unit name="JPATest" >
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<class>test.entities.MyEntity</class>
</persistence-unit>
</persistence>
I have also tried adding the setting to the persistence unit xml:
<property name="hibernate.current_session_context_class" value="thread"/>
It would be nice to not have to change the @Resource to @PersistenceContext if we can help it. We also are injecting the session factory into other classes using xml that we can not control.
I've tried various settings in the persistence context, in the spring bean settings, but the session is always closed and getCurrentSession() fails.