使用getSessionFactoryGetCurrentSession()的Hibernate EntityManager

nir*_*nir 2 java hibernate jpa

我改变了我的应用程序以使用Hibernate EntityManager(来自Hibernate会话),
但我有一些旧代码(我无法更改这些代码),在下面的代码中使用:

getSessionFactory().getCurrentSession() .

我有sessionFactory的bean,所以上面的代码应该工作,但在运行时我有
HibernateException("No Session found for current thread"),甚至上面的代码是在事务块中执行的.

仅供参考:我检查了事务资源(在调试模式下)并且使用密钥EntityManagerFactory,会话存在但不在SessionFactory下

ben*_*n75 8

我建议你这样做(看起来很hacky,但遗留代码,有时需要)

此解决方案使用Spring TransactionSynchronizationManager和Hibernate 4,但可以适应其他Hibernate版本.

以下是这样的想法:在SessionFactoryBean中使用CurrentSessionContext的自定义实现,此自定义实现将在事务资源中搜索当前事务的实体管理器; 当发现只是调用IIla发布的代码来获取休眠会话时.

去做吧 :

1. hibernate.current_session_context_class在hibernateProperties中定义属性:

<bean id="sessionFactory"
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    ...
    <property name="hibernateProperties">
        <props>
            ...
            <prop key="hibernate.current_session_context_class">
                com.example.jpa.HibernateSessionInEntityManager
            </prop>
        </props>
    </property>
</bean>

<!-- for completness : here are the other relevant beans -->

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
    </property>
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan" value="com.example.jpa.validator"/>
</bean>

<bean id="transactionManager"
      class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="dataSource" ref="dataSource" />
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
Run Code Online (Sandbox Code Playgroud)

2.实现自定义CurrentSessionContext:HibernateSessionInEntityManager.java

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.context.spi.CurrentSessionContext;
import org.hibernate.ejb.EntityManagerImpl;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.persistence.EntityManager;
import java.util.Map;

public class HibernateSessionInEntityManager implements CurrentSessionContext {

    public HibernateSessionInEntityManager() {
    }

    public HibernateSessionInEntityManager(SessionFactory sessionFactory) {
    }

    public HibernateSessionInEntityManager(SessionFactoryImplementor sessionFactory) {
    }

    public Session currentSession() throws HibernateException {
        Map<Object, Object> resourceMap = TransactionSynchronizationManager.getResourceMap();
        for(Object v:resourceMap.values()){
            if(v instanceof EntityManagerHolder){
                return getSessionFromEM(((EntityManagerHolder)v).getEntityManager());
            }
        }
        return null;
    }

    private static Session getSessionFromEM(final EntityManager entityManager)
    {
        final Object emDelegate = entityManager.getDelegate();
        if (emDelegate instanceof EntityManagerImpl)
        {
            return ((EntityManagerImpl) emDelegate).getSession();
        }
        else if (emDelegate instanceof Session)
        {
            return (Session) emDelegate;
        }
        throw new HibernateException("No Session found");
    }
 }
Run Code Online (Sandbox Code Playgroud)

注意所有这些构造函数:Hibernate-4需要一个,SessionFactoryImplementor我认为Hibernate-3需要一个SessionFactory.(可能不需要no-args构造函数)

3.这是一个简单的测试用例,以验证它是否有效

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:ApplicationContext.xml" })
public class HibernateSessionInEntityManagerTest {

    @Autowired
    public SessionFactory sessionFactory;

    @Test
    @Transactional
    public void testGetHibernateSession(){
        Session session = sessionFactory.getCurrentSession();
        Assert.assertNotNull(session);
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望它会有所帮助.(顺便说一下:好问题)

重要说明:如果您有多个EntityManagerFactoryBean,请在查看transactionnal资源时选择好的EntityManagerFactoryBean.(例如,查看关联的entityManagerFactory的persistenceUnitName)