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"/>