1

我试图让 Hibernate 4 和 Spring Transactions 一起玩。在这一点上,我只是想获得一个有效的 Hibernate 设置。

这是调用的方法。当我调用它时,我得到

"org.hibernate.HibernateException: createQuery is not valid without active transaction"



@Autowired
SessionFactory sessionFactory;

@Transactional
public SecurityUserDO findSecurityUser(String email)
{
    Session session = sessionFactory.getCurrentSession();

    Query query = session.createQuery( "from SecurityUserDO where email = :email" );
    query.setString( "email", email );
    return (SecurityUserDO) query.uniqueResult();
}

这是配置:

<!-- use annotations to find beans in this package -->
<context:annotation-config/>
<context:component-scan base-package="com.jelli.phoenix.model" />

<!--  Default session factory. Requires a dataSource bean to be defined in another config.
This works with a embedded data source for integration test setup. For real deployment
the datasource should be a c3p0 pool. -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" autowire="byName"
     depends-on="dataSource">
    <property name="configLocation">    
        <value>
            classpath:hibernate.cfg.xml
        </value>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.current_session_context_class">thread</prop>

            <!-- Database connection settings --> 
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>

            <!-- Caching -->
            <prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
            <prop key="hibernate.cache.use_second_level_cache">false</prop>
            <prop key="hibernate.cache.use_query_cache">false</prop>

            <!-- Performance Settings --> 
            <prop key="hibernate.jdbc.batch_versioned_data">true</prop>
            <prop key="hibernate.jdbc.use_streams_for_binary">true</prop>
            <prop key="hibernate.max_fetch_depth">1</prop>

            <!-- When SQL is logged, pretty-print it --> 
            <prop key="hibernate.format_sql">true</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<!-- Use @Transaction annotations for managing transactions  -->    
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

数据源在另一个文件中指定。

我已经阅读了我能找到的每一篇文章。有几个说要删除

"&lt;prop key="hibernate.current_session_context_class"&gt;thread&lt;/prop&gt;", 

但这会导致getCurrentSession()失败。

4

1 回答 1

2

回答我自己的问题:

正如许多其他地方所概述的那样,问题是我有:

<prop key="hibernate.current_session_context_class">线程</prop>

这会禁用 Spring Transactions,但会在 SessionFactory.getCurrentSession() 不再起作用时产生问题。我的解决方法是编写一个实用程序类来调用 SessionFactory.openSession() 并将会话保存在 ThreadLocal 中。

我不得不说我真的不明白为什么 Spring Transactions 拒绝使用 Hibernate 的基于线程的会话上下文。

于 2013-01-30T22:33:43.620 回答