Can HibernateTemplate coexist with EntityManager?

2020-06-19 04:44发布

问题:

We have a spring 3 application that still uses the deprecated HibernateTemplate for persistence and want to migrate to the more modern JPA EntityManager.

Is it possible to use both APIs in parallel during the migration (possibly even both in a single transaction), so that we can do the migration in small steps?

Or will we have to do it big bang?

回答1:

Sure, why not.

The easiest would be to drop your LocalSessionFactoryBean and HibernateTransactionManager configuration and replace it with LocalContainerEntityManagerFactoryBean and JpaTransactionManager, respectively.

Then to obtain a SessionFactory add the HibernateJpaSessionFactoryBean, which exposes the underlying SessionFactory for the EntityManagerFactory.

This way both technologies should peacefully coexist.

There are some reports that doing this leads to a an exception stating No CurrentSessionContext configured!. If you get it add the following to either your persistence.xml

<property name="hibernate.current_session_context_class" value="org.springframework.orm.hibernate4.SpringSessionContext"/>

or jpaProperties of the LocalContainerEntityManagerFactoryBean.

<property name="jpaProperties">
    <props>
        <prop name="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
    <props>
<property>