22

Hibernate 4 と Spring Transactions を使用する Spring 3.2 アプリケーションがあります。すべてのメソッドがうまく機能し、データベースに正しくアクセスしてエンティティを保存または取得できました。次に、いくつかのマルチスレッドを導入しました。各スレッドが db にアクセスしていたため、Hibernate から次のエラーが発生していました。

org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions

Hibernate構成に追加<prop key="hibernate.current_session_context_class">thread</prop>する必要があるWebから読みましたが、今ではdbにアクセスしようとするたびに次のようになります:

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

ただし、サービス メソッドには の注釈が付けられており@Transactional、 を追加する前はすべて正常に機能してい<prop key="hibernate.current_session_context_class">thread</prop>ました。

メソッドに @Transactional のアノテーションが付けられているのに、トランザクションがないのはなぜですか? どうすればこの問題を解決できますか?

これが私のHibernate構成です(セッションコンテキストプロパティを含む):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

<!-- Hibernate session factory -->
<bean
    id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
    <property name="dataSource" >
        <ref bean="dataSource" />
    </property>
    <property name="hibernateProperties" >
        <props>
            <prop key="hibernate.hbm2ddl.auto">create</prop> 
            <prop key="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.current_session_context_class">thread</prop>  
        </props>
    </property>   
    <property name="annotatedClasses" >
        <list>
            ...
        </list>
    </property> 
</bean>

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

<tx:annotation-driven transaction-manager="transactionManager"/>

4

1 に答える 1

35

spring および spring managed トランザクションを使用する場合、JTA を使用していない限りhibernate.current_session_context_class、プロパティをいじらないでください。

Spring はデフォルトで独自のCurrentSessionContext実装 ( SpringSessionContext ) を設定しますが、自分で設定した場合はそうではありません。基本的に、適切なトランザクション統合を壊しています。

この設定を変更する唯一の理由は、JTA 管理トランザクションを使用する場合はいつでも、JTA と適切に統合するためにこれを設定する必要があるためです。

于 2013-09-17T06:21:08.460 に答える